C# Convert Int To Two Hex Bytes?

11,936

Solution 1

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

Solution 2

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

Regex.Replace(number.ToString("X4"), "..", "0x$0 ").TrimEnd();
Share:
11,936
Jan Tacci
Author by

Jan Tacci

Hello.

Updated on June 04, 2022

Comments

  • Jan Tacci
    Jan Tacci almost 2 years

    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!!!

    • Gir
      Gir almost 12 years
    • brianestey
      brianestey almost 12 years
      Do you mean you want the hex-string representation of the int?
    • Jan Tacci
      Jan Tacci almost 12 years
      All I know is this.... given an integer 16 I need to produce 2 bytes. The first bytes value is 0x00 and the second bytes value is 0x10. This ultimately ends up as 0000 0000 0001 0000 which = 16. My program need to chop the result up. In other words, take the first 8 bits and display it as 0x00 then take the last 8 bits and display it as 0x10. In summary, I need to go from 16 -> 0x00 0x10.
    • Thomas Levesque
      Thomas Levesque almost 12 years
      An int is 32 bits, so you need 4 bytes (8 hex digits) to represent all possible values...
  • Jan Tacci
    Jan Tacci almost 12 years
    I am not going for a string... what I have is an array. There are 2 locations in the array where I need to store the value 16. The first position of the array need 0x00 and the second needs 0x01. Note that these are not strings whats being stored in the array are actually bytes so you can also think of it as array[0]=0 and array[1]=10
  • Ry-
    Ry- almost 12 years
    @TackyTacky: If you need an array, BitConverter (or shifting if it's only the two you need) is more appropriate and hexadecimal is irrelevant.
  • Diego Mijelshon
    Diego Mijelshon almost 12 years
    If I do that alone, the second byte does not get the prefix. But yeah, you can probably craft a more complex regex that takes care of that too.