문제

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.

도움이 되었습니까?

해결책

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");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top