1

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];
}
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
  • 1
    Does this answer your question? [Converting string to byte array in C#](https://stackoverflow.com/questions/16072709/converting-string-to-byte-array-in-c-sharp) – Hogan Jan 24 '23 at 17:37
  • @Hogan I think the goal is to preserve the bytes which are written as hex to string. – Guru Stron Jan 24 '23 at 17:40
  • @GuruStron no idea what you mean -- the answer I linked converts a string to bytes – Hogan Jan 24 '23 at 17:41
  • That's right @Guru Stron – Otávio Zordan Alves Jan 24 '23 at 17:41
  • @Hogan the string clearly has bytes written as hex values. Those needed to be translated back to bytes. – Guru Stron Jan 24 '23 at 17:43
  • @OtávioZordanAlves can you please explain a little bit more. What if there are more then 1 byte stored in the string, the goal is to get only the first one or what? Does it have maximum length? – Guru Stron Jan 24 '23 at 17:44
  • What version of .NET are you targeting? [`Convert.FromHexString(data.Replace("0x", ""))[0]` is available since .NET 5](https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-5.0#system-convert-fromhexstring(system-string)) – Mathias R. Jessen Jan 24 '23 at 17:47
  • @Guru Stron 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 – Otávio Zordan Alves Jan 24 '23 at 17:47
  • 1
    `byte.Parse("0x0f".Substring(2), NumberStyles.HexNumber)` – Mike Mozhaev Jan 24 '23 at 17:52

1 Answers1

2

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
Guru Stron
  • 102,774
  • 10
  • 95
  • 132