【发布时间】:2013-05-08 06:57:08
【问题描述】:
我有一个字符串,并想使用 C# 将其转换为十六进制值的字节数组。
例如,“Hello World!” to byte[] val=new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21};,
我在Converting string value to hex decimal看到如下代码
string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
// Get the integral value of the character.
int value = Convert.ToInt32(letter);
// Convert the decimal value to a hexadecimal value in string form.
string hexOutput = String.Format("0x{0:X}", value);
Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}
我想把这个值放到字节数组中,但不能这样写
byte[] yy = new byte[values.Length];
yy[i] = Convert.ToByte(Convert.ToInt32(hexOutput));
我尝试使用从How to convert a String to a Hex Byte Array? 引用的这段代码,其中我传递了十六进制值 48656C6C6F20576F726C6421,但我得到的十进制值不是十六进制。
public byte[] ToByteArray(String HexString)
{
int NumberChars = HexString.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
}
return bytes;
}
我也尝试了How can I convert a hex string to a byte array?的代码
但是一旦我使用 Convert.ToByte 或 byte.Parse ,值就会变为十进制值。 我该怎么办?
提前致谢
我想将 0x80(即 128)发送到串行端口,但是当我将相当于 128 的字符复制并粘贴到变量“输入”并转换为字节时,我得到了 63(0x3F)。所以我想我需要发送十六进制数组。我想我有错误的想法。请看屏幕截图。
现在,我解决了这个问题来组合字节数组。
string input = "Hello World!";
byte[] header = new byte[] { 2, 48, 128 };
byte[] body = Encoding.ASCII.GetBytes(input);
【问题讨论】:
-
也许您必须先了解Binary numeral system 以及计算机如何处理数据以及二进制数据如何呈现给人类(例如ASCII),然后才能尝试在两者之间进行转换。