简体   繁体   English

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

[英]Converting String to Hex then into Byte Array

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! 如果有人可以向我指出正确的方向,或者给我一小段示例代码,那将是非常棒的!

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.GetBytes (假设您发送ASCII char)来完成从stringbyte[]的转换:

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] . 我上面介绍的方法比较笼统,可以处理0x05163782类的输入string以提供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 . 为了使用,您只需要获取第一个字节(因为byte[]始终为byte[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);

To convert just the hexadecimal string to a number, you could use the System.Convert class like so 要将十六进制字符串仅转换为数字,可以使用System.Convert类,如下所示

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

Substring is used to skip the characters 0x 子字符串用于跳过字符0x

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

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