十六进制有一种表示方法,以0x为前缀。如0x68,0xAA等
现在有一字符串:"68 AA AA AA AA AA AA 68 13 00 DF 16"我想将它转成十六进制表示方法并存放在byte数组中,形式如: byte[] data = new byte[] { 0x68, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x68, 0x13, 0x00, 0xDF, 0x16 };
试过两种方法,但结果都不是以0x为前缀的:
byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier)
Convert.ToByte(str, 16)
现在有一字符串:"68 AA AA AA AA AA AA 68 13 00 DF 16"我想将它转成十六进制表示方法并存放在byte数组中,形式如: byte[] data = new byte[] { 0x68, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x68, 0x13, 0x00, 0xDF, 0x16 };
试过两种方法,但结果都不是以0x为前缀的:
byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier)
Convert.ToByte(str, 16)
所以你用byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier)
完全就可以了……
0x68就是104……
/// <summary>
///
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] HexToByte(string hexString)
{
if (string.IsNullOrEmpty(hexString))
{
hexString = "00";
}
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;
}
/// <summary>
///
/// </summary>
/// <param name="hexString"></param>
/// <param name="discarded"></param>
/// <returns></returns>
public static byte[] GetBytes(string hexString, out int discarded)
{
discarded = 0;
string newString = "";
char c;
// remove all none A-F, 0-9, characters
for (int i = 0; i < hexString.Length; i++)
{
c = hexString[i];
if (Uri.IsHexDigit(c))
newString += c;
else
discarded++;
}
// if odd number of characters, discard last character
if (newString.Length % 2 != 0)
{
discarded++;
newString = newString.Substring(0, newString.Length - 1);
} return HexToByte(newString);
}
{
//remove any spaces from the string
msg = msg.Replace(" ", "");
//create a byte array the length of the
//string divided by 2
byte[] comBuffer = new byte[msg.Length / 2];
//loop through the length of the provided string
for (int i = 0; i < msg.Length; i += 2)
//convert each set of 2 characters to a byte
//and add to the array
comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);
return comBuffer;
}
你可以先这样 string[] data = new string[] { "0x68", "0xAA" };
先保存在string数组当中,设备接收的时候,再转换一下。
现在的问题就是"0x68",怎样变成byte数组元素0x68