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.

1

1 Answer 1

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

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.