Home > Mobile >  Convert a hex string to a byte in C#
Convert a hex string to a byte in C#

Time:01-25

I have a String like this:

String data = "0x0f";

and I would like to leave it as a single byte which represents this hex. Does anyone know what function I can use?

I tried using the following function:

public byte pegarValorHexText(string text)
{
    int NumberChars = text.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i  = 2)
        bytes[i / 2] = Convert.ToByte(text.Substring(i, 2), 16);
    return bytes[0];
}

CodePudding user response:

The string has a hexadecimal value, it has a maximum of 4 characters, the sequence "0x" indicating that it is a hexadecimal value and a sequence of two hex chars

Just use Convert.ToByte then, it should handle the hex prefix:

byte b = Convert.ToByte("0x0f", 16); // 15
  • Related