1

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 ?

3
  • 1
    The code isn't even valid. You can't assign 0x01 to a string. Fix it to the actual string you have. Commented Sep 14, 2016 at 13:06
  • Sorry I quickly type the top to try an explain the problem. Commented Sep 14, 2016 at 13:08
  • Are you only going to convert strings on the format of 0x?? or do you need to support binary, octal, decimal as well? Commented Sep 14, 2016 at 13:23

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

8 Comments

Why convert first to int? ToByte also accepts radix.
Just another way.
Sorry, I don't follow. Why add another unnecessary step? Convert.ToByte("0xef", 16) works correctly.
Kiziu is correct: You don't need to strip off the 0x and you don't need to convert to an int first.
Remove the second suggestion. Thanks.
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.