Convert string "0x32" to one byte

I am working with C # trying to convert a string value to a byte. It seems to be harder than I expected. Basically, I have a string called hex = "0x32" and need a byte block for this value.

string hex = "0x32";
byte block = Convert.ToByte(hex);

The above does not work, does anyone know how I can successfully assign a hex value to a byte. I need to add this byte to the byte array later in the code.

+3
source share
3 answers

Try to execute

byte block = Byte.Parse(hex.SubString(2), NumberStyles.HexNumber);

The reason for the call SubStringis to remove the preceding "0x" from the string. Parse function does not expect the prefix "0x", even if specified NumberStyles.HexNumberand an error will occur if it occurs

+4
Convert.ToByte(hex, 16)
+2
    string hex = "0x32";
    int value = Convert.ToInt32(hex, 16);
    byte byteVal = Convert.ToByte(value);

...

Edit

, , 0x32 (hex) 50 (int) .

    string hex = "0x32";
    byte[] byteVal = new byte[1];
    byteVal[0] = Convert.Byte(hex, 16);
    Console.WriteLine(byteVal[0] + " - Integer value");
    Console.WriteLine(BitConverter.ToString(byteVal) + " - BitArray representation");;
+1

Source: https://habr.com/ru/post/1760619/


All Articles