How can I convert the following?
2934 (integer) to B76 (hex)
Let me explain what I am trying to do. I have User IDs in my database that are stored as integers. Rather than having users reference their IDs I want to let them use the hex value. The main reason is because it's shorter.
So not only do I need to go from integer to hex but I also need to go from hex to integer.
Is there an easy way to do this in C#?
An integer can be converted to a hexadecimal by using the string. ToString() extension method.
Take decimal number as dividend. Divide this number by 16 (16 is base of hexadecimal so divisor here). Store the remainder in an array (it will be: 0 to 15 because of divisor 16, replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Repeat the above two steps until the number is greater than zero.
X = hex2num( hexStr ) converts hexStr to the double-precision floating-point number that it represents. The input argument hexStr has up to 16 characters representing a number in its IEEE® format using hexadecimal digits.
The hexadecimal value of a negative decimal number can be obtained starting from the binary value of that decimal number positive value. The binary value needs to be negated and then, to add 1. The result (converted to hex) represents the hex value of the respective negative decimal number.
// Store integer 182 int intValue = 182; // Convert integer 182 as a hex in a string variable string hexValue = intValue.ToString("X"); // Convert the hex string back to the number int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
from http://www.geekpedia.com/KB8_How-do-I-convert-from-decimal-to-hex-and-hex-to-decimal.html
HINT (from the comments):
Use .ToString("X4")
to get exactly 4 digits with leading 0, or .ToString("x4")
for lowercase hex numbers (likewise for more digits).
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