开发者

Convert string "0x32" into a single byte

I'm working with C# trying to convert a string value into a byte. Seems to be harder then I expected. Basically I have a string called hex = "0x32" and need byte block to equal this value.

string hex = "0x32";
byte block = Convert.ToByte(hex);

The above doesn't work, does anybody know how I can successfully assign the hex value to the byte. I need to append this byte to a byte a开发者_如何转开发rray later in the code.


Try the following

byte block = Byte.Parse(hex.SubString(2), NumberStyles.HexNumber);

The reason for the SubString call is to remove the preceeding "0x" from the string. The Parse function does not expect the "0x" prefix even when NumberStyles.HexNumber is specified and will error if encountered


Convert.ToByte(hex, 16)


    string hex = "0x32";
    int value = Convert.ToInt32(hex, 16);
    byte byteVal = Convert.ToByte(value);

Will work...

Edit

A little code to demonstrate that 0x32 (hex) and 50 (int) are the same.

    string hex = "0x32";
    byte[] byteVal = new byte[1];
    byteVal[0] = Convert.Byte(hex, 16);
    Console.WriteLine(byteVal[0] + " - Integer value");
    Console.WriteLine(BitConverter.ToString(byteVal) + " - BitArray representation");;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜