1byte a = 0xF9; 2string high = Convert.ToString((a & 0xf0) >> 4);// 这里的位操作数以及位移的数目可以根据自己的需要修改 3string low = Convert.ToString(a & 0x0f);// 这里的位操作数以及位移的数目可以根据自己的需要修改
byte和string的转换
1private static byte[] HexToByte(string hexString) 2 { 3 byte[] returnBytes = new byte[hexString.Length / 2]; 4 for (int i = 0; i < returnBytes.Length; i++) 5 returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); 6 return returnBytes; 7 }
应用例子,对byte按位取反后得到byte
1private byte GetOppData(byte bData) { 2 3 string s = Convert.ToString(bData, 16); 4 int d = Convert.ToUInt16(s, 16); 5 d = ~d; 6 string sdata = Convert.ToString(d, 16); 7 Console.WriteLine(sdata); 8 string realSData = sdata.Substring(6); 9 Console.WriteLine(realSData); 10 byte[] bHex=HexToByte(realSData); 11 return bHex[0]; 12 } 13 14//string类型转成byte[]: 15 16byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str ); 17 18//byte[]转成string: 19string str = System.Text.Encoding.Default.GetString ( byteArray ); 20 21//其它编码方式的,如System.Text.UTF8Encoding,System.Text.UnicodeEncoding class等;例如:string类型转成ASCII byte[]:("01" 转成 byte[] = new byte[]{ 0x30, 0x31}) 22byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str ); 23 24//ASCII byte[] 转成string:(byte[] = new byte[]{ 0x30, 0x31} 转成 "01") 25string str = System.Text.Encoding.ASCII.GetString ( byteArray );