将字符串转换为十六进制,然后转换为字节数组

时间:2022-11-30 15:45:14

So, I have a string that I want to convert each character to hex values and then put it in a byte array to be sent through a com port.

因此,我有一个字符串,我想要将每个字符转换为十六进制值,然后将它放入一个字节数组中,然后通过com端口发送。

I can convert the individual characters to the hex that I need to send, but I can't get that array of strings into a byte array correctly.

我可以将单个字符转换为我需要发送的十六进制字符,但是我不能将字符串数组正确地转换为字节数组。

example:

例子:

string beforeConverting = "HELLO";

String[] afterConverting = {"0x48", "0x45", "0x4C", "0x4C", "0x4F"};

should become

应该成为

byte[] byteData = new byte[]{0x48, 0x45, 0x4C, 0x4C, 0x4F};

I've tried several different things from several different posts but I can't get the right combination of things together. If anyone could point me in the right direction or give me a snippet of example code that would be awesome!

我从几个不同的帖子中尝试了几件不同的事情,但是我不能把所有的东西组合在一起。如果有人能给我指出正确的方向,或者给我一个示例代码片段,那将是非常棒的!

2 个解决方案

#1


3  

If your final aim is to send byte[], then you can actually skip the middle step and immediately do the conversion from string to byte[] using Encoding.ASCII.GetBytes (provided that you send ASCII char):

如果您的最终目标是发送byte[],那么您实际上可以跳过中间步骤,立即使用Encoding.ASCII从字符串转换为byte[]。GetBytes(提供您发送的ASCII字符):

string beforeConverting = "HELLO";
byte[] byteData = Encoding.ASCII.GetBytes(beforeConverting); 
//will give you {0x48, 0x45, 0x4C, 0x4C, 0x4F};

If you don't send ASCII, you could find the appropriate Encoding type (like Unicode or UTF32), depends on your need.

如果不发送ASCII,可以根据需要找到合适的编码类型(如Unicode或UTF32)。

That being said, if you still want to convert the hex string to byte array, you could do something something like this:

也就是说,如果你还想把十六进制字符串转换成字节数组,你可以这样做:

/// <summary>
/// To convert Hex data string to bytes (i.e. 0x01455687)  given the data type
/// </summary>
/// <param name="hexString"></param>
/// <param name="dataType"></param>
/// <returns></returns>
public static byte[] HexStringToBytes(string hexString) {
  try {
    if (hexString.Length >= 3) //must have minimum of length of 3
      if (hexString[0] == '0' && (hexString[1] == 'x' || hexString[1] == 'X'))
        hexString = hexString.Substring(2);
    int dataSize = (hexString.Length - 1) / 2;
    int expectedStringLength = 2 * dataSize;
    while (hexString.Length < expectedStringLength)
      hexString = "0" + hexString; //zero padding in the front
    int NumberChars = hexString.Length / 2;
    byte[] bytes = new byte[NumberChars];
    using (var sr = new StringReader(hexString)) {
      for (int i = 0; i < NumberChars; i++)
        bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
    }
    return bytes;
  } catch {
    return null;
  }
}

And then use it like this:

然后像这样使用它:

byte[] byteData = afterConverting.Select(x => HexStringToBytes(x)[0]).ToArray();

The method I put above is more general which can handle input string like 0x05163782 to give byte[4]. For your use, you only need to take the first byte (as the byte[] will always be byte[1]) and thus you have [0] index in the LINQ Select.

我上面的方法更一般,它可以处理输入字符串比如0x05163782,从而给出字节[4]。对于您的使用,您只需要取第一个字节(因为字节[]总是字节[1]),因此您在LINQ Select中有[0]索引。

The core method used in the custom method above is Convert.ToByte():

上述自定义方法中使用的核心方法是Convert.ToByte():

bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);

#2


1  

To convert just the hexadecimal string to a number, you could use the System.Convert class like so

要将十六进制字符串转换为数字,可以使用系统。转换类一样

string hex = "0x3B";
byte b = Convert.ToByte(hex.Substring(2), 16)
// b is now 0x3B

Substring is used to skip the characters 0x

子字符串用于跳过字符0x

#1


3  

If your final aim is to send byte[], then you can actually skip the middle step and immediately do the conversion from string to byte[] using Encoding.ASCII.GetBytes (provided that you send ASCII char):

如果您的最终目标是发送byte[],那么您实际上可以跳过中间步骤,立即使用Encoding.ASCII从字符串转换为byte[]。GetBytes(提供您发送的ASCII字符):

string beforeConverting = "HELLO";
byte[] byteData = Encoding.ASCII.GetBytes(beforeConverting); 
//will give you {0x48, 0x45, 0x4C, 0x4C, 0x4F};

If you don't send ASCII, you could find the appropriate Encoding type (like Unicode or UTF32), depends on your need.

如果不发送ASCII,可以根据需要找到合适的编码类型(如Unicode或UTF32)。

That being said, if you still want to convert the hex string to byte array, you could do something something like this:

也就是说,如果你还想把十六进制字符串转换成字节数组,你可以这样做:

/// <summary>
/// To convert Hex data string to bytes (i.e. 0x01455687)  given the data type
/// </summary>
/// <param name="hexString"></param>
/// <param name="dataType"></param>
/// <returns></returns>
public static byte[] HexStringToBytes(string hexString) {
  try {
    if (hexString.Length >= 3) //must have minimum of length of 3
      if (hexString[0] == '0' && (hexString[1] == 'x' || hexString[1] == 'X'))
        hexString = hexString.Substring(2);
    int dataSize = (hexString.Length - 1) / 2;
    int expectedStringLength = 2 * dataSize;
    while (hexString.Length < expectedStringLength)
      hexString = "0" + hexString; //zero padding in the front
    int NumberChars = hexString.Length / 2;
    byte[] bytes = new byte[NumberChars];
    using (var sr = new StringReader(hexString)) {
      for (int i = 0; i < NumberChars; i++)
        bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
    }
    return bytes;
  } catch {
    return null;
  }
}

And then use it like this:

然后像这样使用它:

byte[] byteData = afterConverting.Select(x => HexStringToBytes(x)[0]).ToArray();

The method I put above is more general which can handle input string like 0x05163782 to give byte[4]. For your use, you only need to take the first byte (as the byte[] will always be byte[1]) and thus you have [0] index in the LINQ Select.

我上面的方法更一般,它可以处理输入字符串比如0x05163782,从而给出字节[4]。对于您的使用,您只需要取第一个字节(因为字节[]总是字节[1]),因此您在LINQ Select中有[0]索引。

The core method used in the custom method above is Convert.ToByte():

上述自定义方法中使用的核心方法是Convert.ToByte():

bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);

#2


1  

To convert just the hexadecimal string to a number, you could use the System.Convert class like so

要将十六进制字符串转换为数字,可以使用系统。转换类一样

string hex = "0x3B";
byte b = Convert.ToByte(hex.Substring(2), 16)
// b is now 0x3B

Substring is used to skip the characters 0x

子字符串用于跳过字符0x