How can I convert this string into a byte?
string a = "0x2B";
I tried this code, (byte)(a); but it said:
Cannot convert type string to byte...
And when I tried this code, Convert.ToByte(a);
and this byte.Parse(a);
, it said:
Input string was not in a correct format...
What is the proper code for this?
But when I am declaring it for example in an array, it is acceptable...
For example:
byte[] d = new byte[1] = {0x2a};
To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.
Each Hexadecimal character represents 4 bits (0 - 15 decimal) which is called a nibble (a small byte - honest!). A byte (or octet) is 8 bits so is always represented by 2 Hex characters in the range 00 to FF.
You can use UTF8Encoding:
public static byte[] StrToByteArray(string str)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}
You have to specify the base to use in Convert.ToByte
since your input string contains a hex number:
byte b = Convert.ToByte(a, 16);
You can use the ToByte function of the Convert helper class:
byte b = Convert.ToByte(a, 16);
Update:
As others have mentioned, my original suggestion to use byte.Parse()
with NumberStyles.HexNumber
actually won't work with hex strings with "0x" prefix. The best solution is to use Convert.ToByte(a, 16)
as suggested in other answers.
Original answer:
Try using the following:
byte b = byte.Parse(a, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
byte b = Convert.ToByte(a, 16);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With