Jan Tacci
Jan Tacci

Reputation: 3211

C# Convert Int To Two Hex Bytes?

I have an integer that I need to convert to a four digit hex value.

For example, lets say the int value is 16. What I am looking for is a way to go from 16 to 0x00 0x10.

Any suggestions would be greatly appreciated!!!

Upvotes: 5

Views: 13100

Answers (4)

dtb
dtb

Reputation: 217313

Try this:

var input = 16;

var bytes = new byte[2];
bytes[0] = (byte)(input >> 8);  // 0x00
bytes[1] = (byte)input;         // 0x10

var result = (bytes[0] << 8)
           | bytes[1];

// result == 16

Upvotes: 3

Diego Mijelshon
Diego Mijelshon

Reputation: 52725

Here's one with regular expressions, just for fun:

Regex.Replace(number.ToString("X4"), "..", "0x$0 ").TrimEnd();

Upvotes: 1

Ry-
Ry-

Reputation: 224922

Shift it! Mask it! Mask it! string.Format it!

int n = 16;
string.Format("0x{0:x2} 0x{1:x2}", (n & 0xff00) >> 8, n & 0xff); // 0x00 0x10

Here's a demo.

The x2 format specifier means a 2-digit hexadecimal value.


Okay, apparently you just want two bytes. Hexadecimal is not relevant here.

byte lowByte = (byte)(n & 0xff);
byte highByte = (byte)(n >> 8 & 0xff);

Upvotes: 0

K893824
K893824

Reputation: 1319

Alternately, a little more general solution is to do it by byte array (then you can use this for strings or other data types)

public static string ByteArrayToString(byte[] ba)
{
   string hex = BitConverter.ToString(ba);
   return hex.Replace("-","");
}

int i = 39;
string str = "ssifm";
long l = 93823;

string hexi = ByteArrayToString(BitConverter.GetBytes(i));
string hexstr = ByteArrayToString(Encoding.Ascii.GetBytes(str));
string hexl = ByteArrayToString(BitConverter.GetBytes(l));

This returns them in a 'FF' format, you can add the '0x' yourself by adding this after the ToString() instead:

return "0x"+hex.Replace("-", " 0x");

Upvotes: 0

Related Questions