I'm working with C# trying to convert a string value into a byte. Seems to be harder then I expected. Basically I have a string called hex = "0x32" and need byte block to equal this value.
string hex = "0x32";
byte block = Convert.ToByte(hex);
The above doesn't work, does anybody know how I can successfully assign the hex value to the byte. I need to append this byte to a byte array later in the code.
Try the following
byte block = Byte.Parse(hex.SubString(2), NumberStyles.HexNumber);
The reason for the SubString
call is to remove the preceeding "0x" from the string. The Parse function does not expect the "0x" prefix even when NumberStyles.HexNumber
is specified and will error if encountered
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With