Search code examples
c#hex

Convert int to hex format 0xyy c#


I need to write a function which receives one parametrer of type int (decimal), and returns string containing the int value in hex, but in format 0xyy.
More than that I want the answer to be in a fixed format of 4 Bytes For example:

int b = 358;
string ans = function(b); 

In this case ans = "0x00 0x00 0x01 0x66"

int a = 3567846; 
string ans = function(a);

In this case ans = "0x00 0x36 0x70 0xE6"


Solution

  • This should match your examples:

    static string Int32ToBigEndianHexByteString(Int32 i)
    {
        byte[] bytes = BitConverter.GetBytes(i);
        string format = BitConverter.IsLittleEndian
            ? "0x{3:X2} 0x{2:X2} 0x{1:X2} 0x{0:X2}"
            : "0x{0:X2} 0x{1:X2} 0x{2:X2} 0x{3:X2}";
        return String.Format(format, bytes[0], bytes[1], bytes[2], bytes[3]);
    }