c#中string与byte[]的转化

来源:互联网 发布:程序员薪资15*15 编辑:程序博客网 时间:2024/06/06 02:35


string类型转成byte[]:

byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );

[例]

str="01A";

byteArray = {0x48 , 0x49 , 0x65};

反过来,byte[]转成string:

string str = System.Text.Encoding.Default.GetString ( byteArray );


其它编码方式的,如System.Text.UTF8Encoding,System.Text.UnicodeEncoding class等;


string类型转成ASCII byte[]:("01" 转成 byte[] = new byte[]{ 0x30, 0x31})

byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str );

ASCII byte[] 转成string:(byte[] = new byte[]{ 0x30, 0x31} 转成 "01")

string str = System.Text.Encoding.ASCII.GetString ( byteArray );



string 转十六进制 byte[]
private byte[] StringToHex(string s)
        {
            s = s.Replace(" ", "");
            if ((s.Length % 2) != 0)
            {
                s += "";
            }
            byte[] bytes = new byte[s.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = Convert.ToByte(s.Substring(i * 2, 2), 16);
            }
            return bytes;
        }
[例]  str = "CB35";  byte[] = {0xCB ,  0x35} (即十进制的102和53) 即按str每两位是一十六进制数,转化为十进制的byte存储


string(仅数字) 保留原字符转 byte[]
public static byte[] StrToByte6(string input) 
        {
            const int maxlen = 6;//数组长度要根据string长度来定,长度是string长度的一半
            byte[] abyte = new byte[maxlen];
            //每次转换两个数字
            for (int i = 0; i < maxlen; i++)
            {
                string temp = input.Substring(i * 2, 2);
                int Num = Convert.ToInt32(temp);
                abyte[i] = System.BitConverter.GetBytes(Num)[0];
            }
            return abyte;
        }

[例]  str = "0135";  byte[] = {0x01 ,  0x35}   str长度为4,转化后byte长度为2



0 0