Hunter Dishner
Hunter Dishner

Reputation: 60

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.

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!

Upvotes: 2

Views: 2355

Answers (2)

Ian
Ian

Reputation: 30813

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):

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.

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.

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

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

Upvotes: 3

Jan Kytka
Jan Kytka

Reputation: 333

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

Upvotes: 2

Related Questions