c#中string与byte[]的转化



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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值