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

Edited 6 Years Ago by Smithy566: n/a

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);

Thank you both, your solutions worked!

Edited 6 Years Ago by Smithy566: n/a

This question has already been answered. Start a new discussion instead.