Convert a number into the hex value in .NET

20,797

Solution 1

One way would be to append the number of digits you need, after "x". This will pad the output with leading zeros as necessary.

"0x" + myLong.ToString("x16");

or

string.Format("0x{0:x16}", myLong);

From The Hexadecimal ("X") Format Specifier :

The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.

Solution 2

string hex = "0x" + int.ToString("x16")
Share:
20,797
Alex
Author by

Alex

.net developer

Updated on October 27, 2020

Comments

  • Alex
    Alex over 3 years

    I need to convert an integer number to the hex value. It will look like this:

    0x0201cb77192c851c

    When I do

    string hex = int.ToString("x")
    

    in C#, it returns

    201cb77192c851c
    

    How can I get the required result?

  • gabac
    gabac over 13 years
    well, your answer works, if i upvote yours will you upvote mine lol
  • Ani
    Ani over 13 years
    @John Boker: Thanks, but yours needs the precision specifier.
  • gabac
    gabac over 13 years
    @ani the precision specifier wasnt in the specs.
  • Ani
    Ani over 13 years
    @John Boker: Note the leading zero in the OP's sample.
  • gabac
    gabac over 13 years
    @ani, you are correct, im drunk, disregard what i say... i want 13k, almost there. :)
  • gabac
    gabac over 13 years
    @ani i added the 16 to my x. i shouldnt drink on a work nigth.
  • royalTS
    royalTS over 3 years
    should be 'int.ToString("x8")', or? 4 bytes, two places = 8