Use methods in the Convert
class to parse the string to a number. To parse an unsigned 2 byte value you use the ToUInt16
method, and specify the base 16:
ushort value = Convert.ToUInt16("0xFFFF", 16);
Use these methods for other format:
ToInt16 = signed 2 byte
ToUInt32 = unsigned 4 byte
ToInt32 = signed 4 byte
ToByte = unsigned 1 byte
ToSByte = signed 1 byte
To format a number to a hexadecimal string you can use the X
format (or x
to get lower case letters) and specify the number of digits:
string formatted = value.ToString("X4");
That will however not have the 0x
prefix, so if you want that you have to add it:
string formatted = "0x" + value.ToString("X4");