C# convert integer to hex 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#?
// 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
Use:
int myInt = 2934;
string myHex = myInt.ToString("X"); // Gives you hexadecimal
int myNewInt = Convert.ToInt32(myHex, 16); // Back to int again.
See How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide) for more information and examples.
Try the following to convert it to hex
public static string ToHex(this int value) {
return String.Format("0x{0:X}", value);
}
And back again
public static int FromHex(string value) {
// strip the leading 0x
if ( value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) {
value = value.Substring(2);
}
return Int32.Parse(value, NumberStyles.HexNumber);
}
链接地址: http://www.djcxy.com/p/87790.html
上一篇: 如何使用Java将hex转换为rgb?
下一篇: C#将整数转换为十六进制并再次返回