如何将字符串转换为字节数组

时间:2013-05-14 05:19:15

标签: c# string bytearray

我有一个字符串,想要使用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的字符复制并粘贴到变量'input'并转换为byte时,我得到了63(0x3F)。所以我想我需要发送十六进制数组。我想我的想法错了。请看屏幕截图。

enter image description here

现在,我解决这个问题来组合字节数组。

string input = "Hello World!";
byte[] header = new byte[] { 2, 48, 128 };
byte[] body = Encoding.ASCII.GetBytes(input);

4 个答案:

答案 0 :(得分:3)

十六进制与此无关,您想要的结果只不过是包含ASCII代码的字节数组。

尝试Encoding.ASCII.GetBytes(s)

答案 1 :(得分:0)

你的要求有些奇怪:

  

我有一个字符串,想要将其转换为字符串数组的十六进制值   使用C#。

字节只是一个8位值。您可以将其显示为十进制(例如16)或十六进制(例如0x10)。

那么,你真正想要的是什么?

答案 2 :(得分:0)

如果你真的想要获得一个包含字节数组的十六进制表示的字符串,那么你可以这样做:

public static string BytesAsString(byte[] bytes)
{
    string hex = BitConverter.ToString(bytes); // This puts "-" between each value.
    return hex.Replace("-","");                // So we remove "-" here.
}

答案 3 :(得分:0)

看起来你正在混合转换为数组并显示数组数据。

当你有字节数组时,它只是字节数组,你可以用任何可能的方式表示二进制,十进制,十六进制,八进制,等等......但只有在你想直观地表示这些时才有效。

这是一个代码,它手动将字符串转换为字节数组,然后转换为十六进制格式的字符串数组。

string s1 = "Stack Overflow :)";
byte[] bytes = new byte[s1.Length];
for (int i = 0; i < s1.Length; i++)
{
      bytes[i] = Convert.ToByte(s1[i]);
}

List<string> hexStrings = new List<string>();

foreach (byte b in bytes)
{
     hexStrings.Add(Convert.ToInt32(b).ToString("X"));
}