Member Avatar for Smithy566

Hi all,

I'm having a bit of trouble trying to convert a string which represents hex, to a byte.

Logic below, something like this:

String hexString = "0x5C";
Byte myNewByte;

myNewByte = Byte.Parse(hexString);

Error: "The input string was not in a correct format"

I know I can have a byte with a value of '0x5C' but finding this troublesome! This should be straight forward. I just want to have a byte with the value represented by the string.

Any help would be much appreciated

The default base is 10.
Try this

myNewByte = System.Convert.ToByte(hexString, 16);
String hexString = "0x5C";
Byte myNewByte;

myNewByte = Byte.Parse(hexString);

Error: "The input string was not in a correct format"

Byte.Parse() with just a string parameter doesn't know that "0x" means hexadecimal. What you need is the overload of Byte.Parse() that lets you tell it to look for hex. You'll need to give it NumberStyles.AllowHexSpecifier or NumberStyles.HexNumber, and you can't use the "0x" at the front either... you'll need to strip that out first.

Something like this:

String hexString = "0x5C";
Byte myNewByte;

myNewByte = Byte.Parse(hexString.Replace("0x", ""), NumberStyles.HexNumber);
Member Avatar for Smithy566

Thank you both, your solutions worked!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.