简体   繁体   English

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

[英]How to convert a string to byte array

I have a string and want to convert it to a byte array of hex value using C#. 我有一个字符串,并希望使用C#将其转换为十六进制值的字节数组。
for eg, "Hello World!" 例如,“Hello World!” to byte[] val=new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21};, to byte [] val = new byte [] {0x48,0x65,0x6C,0x6C,0x6F,0x20,0x57,0x6F,0x72,0x6C,0x64,0x21} ;,

I see the following code in 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);
}

I want this value into byte array but can't write like this 我希望这个值成为字节数组但不能这样写

byte[] yy = new byte[values.Length];
yy[i] = Convert.ToByte(Convert.ToInt32(hexOutput));

I try this code referenced from How to convert a String to a Hex Byte Array? 我尝试从如何将字符串转换为十六进制字节数组引用的代码 where I passed the hex value 48656C6C6F20576F726C6421 but I got the decimal value not hex. 我通过十六进制值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;
}

and I also try code from How can I convert a hex string to a byte array? 我也尝试从如何将十六进制字符串转换为字节数组的代码?

But once I used Convert.ToByte or byte.Parse , the value change to decimal value. 但是一旦我使用Convert.ToByte或byte.Parse,值就会变为十进制值。 How should I do? 我应该怎么做?

Thanks in advance 提前致谢

I want to send 0x80 (ie, 128) to serial port but when I copy and paste the character equivalent to 128 to the variable 'input' and convert to byte, I got 63 (0x3F). 我想将0x80(即128)发送到串口,但是当我将相当于128的字符复制并粘贴到变量'input'并转换为byte时,我得到了63(0x3F)。 So I think I need to send hex array. 所以我想我需要发送十六进制数组。 I think I got the wrong idea. 我想我的想法错了。 Pls see screen shot. 请看屏幕截图。

在此输入图像描述

For now, I solve this to combine byte arrays. 现在,我解决这个问题来组合字节数组。

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

Hexadecimal has nothing to do with this, your desired result is nothing more nor less than an array of bytes containing the ASCII codes. 十六进制与此无关,您所需的结果只不过是包含ASCII代码的字节数组。

Try Encoding.ASCII.GetBytes(s) 尝试Encoding.ASCII.GetBytes(s)

There's something strange with your requirement: 您的要求有些奇怪:

I have a string and want to convert it to a byte array of hex value using C#. 我有一个字符串,并希望使用C#将其转换为十六进制值的字节数组。

An byte is just an 8-bit value. 一个字节只是一个8位值。 You can present it as decimal (eg 16) or hexidecimal (eg 0x10). 您可以将其显示为十进制(例如16)或十六进制(例如0x10)。

So, what do you realy want? 那么,你真正想要的是什么?

In case you are really wanting to get a string which contains the hex representation of an array of bytes, here's how you can do that: 如果你真的想要获得一个包含字节数组的十六进制表示的字符串,那么你可以这样做:

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

It seems like you're mixing converting to array and displaying array data. 看起来你正在混合转换为数组并显示数组数据。

When you have array of bytes it's just array of bytes and you can represent it in any possible way binary, decimal, hexadecimal, octal, whatever… but that is only valid if you want to visually represent these. 当你有字节数组时,它只是字节数组,你可以用任何可能的方式表示二进制,十进制,十六进制,八进制,等等...但只有在你想要直观地表示它们时才有效。

Here is a code that manually converts string to byte array and then to array of strings in hex format. 这是一个代码,它手动将字符串转换为字节数组,然后转换为十六进制格式的字符串数组。

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"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM