0

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"

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
cheziHoyzer
  • 4,803
  • 12
  • 54
  • 81
  • http://stackoverflow.com/questions/1139957/c-sharp-convert-integer-to-hex-and-back-again – andy Jan 02 '13 at 12:05

3 Answers3

5

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]);
}
Rawling
  • 49,248
  • 7
  • 89
  • 127
1

I think the format you want is on similar lines

int ahex = 3567846;
byte[] inthex = BitConverter.GetBytes(ahex);
Console.WriteLine("0x"+ BitConverter.ToString(inthex).Replace("-"," 0x"));
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
0
int val = 1;
string conv = ("0x" + val.ToString("X4"));
  • Answer needs supporting information Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](https://stackoverflow.com/help/how-to-answer). – moken Aug 05 '23 at 04:55