C#字节取高低位以及byte和string的转换

byte a = 0xF9;
string high = Convert.ToString((a & 0xf0) >> 4);// 这里的位操作数以及位移的数目可以根据自己的需要修改
string low = Convert.ToString(a & 0x0f);// 这里的位操作数以及位移的数目可以根据自己的需要修改

 byte和string的转换

 private static byte[] HexToByte(string hexString)
        {
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

应用例子,对byte按位取反后得到byte

private byte GetOppData(byte bData) {

            string s = Convert.ToString(bData, 16);
            int d = Convert.ToUInt16(s, 16);
            d = ~d;
            string sdata = Convert.ToString(d, 16);
            Console.WriteLine(sdata);
            string realSData = sdata.Substring(6);
            Console.WriteLine(realSData);
            byte[] bHex=HexToByte(realSData);
            return bHex[0];
        }
 //string类型转成byte[]: 

byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );
//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 );

引用: https://bbs.csdn.net/topics/370198959

posted on 2018-11-21 10:17  AlexGui  阅读(7559)  评论(0编辑  收藏  举报

导航