Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer to hexadecimal and back again

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#?

like image 540
codette Avatar asked Jul 16 '09 20:07

codette


People also ask

Which method converts an int value into its equivalent hexadecimal?

An integer can be converted to a hexadecimal by using the string. ToString() extension method.

How do you convert a number to hexadecimal?

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.

How do you convert hexadecimal to double?

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.

How do you convert a negative number to hexadecimal?

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.


1 Answers

// 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).

like image 68
Gavin Miller Avatar answered Nov 15 '22 23:11

Gavin Miller