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?
if you need to represent in C# an hexadecimal constant, prefix it with 0x , as you are used to do in C.
To convert an integer to string in C#, use the ToString() method.
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.
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.
string hex = "0x" + int.ToString("x16")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With