Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string "0x32" into a single byte

Tags:

c#

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.

like image 489
user400383 Avatar asked Jan 22 '23 14:01

user400383


1 Answers

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

like image 160
JaredPar Avatar answered Feb 09 '23 10:02

JaredPar