Reputation: 25
I need a bit of help, How would I go about converting the below to a byte.
string s = "0x01";
byte b = Convert.toByte(s); //(Tried this) ??
byte c = byte.Parse(s); //(Tried this as well)
How would I convert s to a byte ?
Upvotes: 1
Views: 2386
Reputation: 100
Firstly, remove "0x" from the string value and then use parse() method with NumberStyles.HexNumber
string s = "AA";
byte byteValue = 0;
try
{
byteValue = byte.Parse(s, NumberStyles.HexNumber | NumberStyles.AllowHexSpecifier);
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("String value: 0x{0}, byte value: {1}", s, byteValue);
Upvotes: 0
Reputation: 1947
I guess the parse function won't allow the prefix 0X in the string so you might use sub-string to remove it.
byte myByte = Byte.Parse(s.SubString(2), NumberStyles.HexNumber);
Or use -
byte myByte = Convert.ToByte(s,16);
Upvotes: 4