2

I need a function to convert hex values in the format 0xFFFF (2 Bytes) to decimal (unsigned and signed).

For example:

0xFFFE is 65534 (unsigned)
0xFFFE is -2 (signed)

I need also the same thing for 4 Bytes and 1 Byte.

All these options (3 * 2 options) I need to convert back - from decimal to hex (total 12 options).

My function should look like this:

    string Myconverter(int ByteSize, bool IsFromHextoDecimal, bool IsSigned)
    {
        ...
    }

If there's build in functionality that performs these conversions, I'd like to a reference/link.

John Willemse
  • 6,608
  • 7
  • 31
  • 45
cheziHoyzer
  • 4,803
  • 12
  • 54
  • 81
  • 1
    Have a look at [How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/bb311038.aspx) (courtesy of MSDN) – Nolonar Apr 15 '13 at 09:09

1 Answers1

3

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");
Guffa
  • 687,336
  • 108
  • 737
  • 1,005