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
  • 156,531
  • 20
  • 258
  • 446
cheziHoyzer
  • 4,050
  • 10
  • 44
  • 71
  • http://stackoverflow.com/questions/1139957/c-sharp-convert-integer-to-hex-and-back-again – andy Jan 02 '13 at 12:05

2 Answers2

4

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
  • 45,907
  • 6
  • 80
  • 115
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
  • 34,000
  • 7
  • 73
  • 81