Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a number into the hex value in .NET

Tags:

string

c#

hex

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?

like image 805
Alex Avatar asked Oct 29 '10 04:10

Alex


People also ask

How do you write hex numbers in C#?

if you need to represent in C# an hexadecimal constant, prefix it with 0x , as you are used to do in C.

How do I convert an int to a string in C#?

To convert an integer to string in C#, use the ToString() method.

How do you convert hex?

The conversion of hexadecimal to decimal is done by using the base number 16. The hexadecimal digit is expanded to multiply each digit with the power of 16. The power starts at 0 from the right moving forward towards the right with the increase in power. For the conversion to complete, the multiplied numbers are added.

Does Atoi convert hex?

atoi(s[,base]) converts a string into an integer. The default is decimal, but you can specify octal 8, hexadecimal 16, or decimal 10. If 0 is the base, the string will be parsed as a hexadecimal if it has a leading 0x and as an octal if it has a leading 0. Otherwise, it will be treated as a decimal.


2 Answers

string hex = "0x" + int.ToString("x16")
like image 45
John Boker Avatar answered Sep 17 '22 16:09

John Boker


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.

like image 142
Ani Avatar answered Sep 18 '22 16:09

Ani