In my system,i need to add 2 Hexa values.So, how can i add hexa values in C#? And i also want to know the max length of Hexa values and which Instance hold these values.
6 Answers
C# supports hexadecimal literals:
int i = 0xff;
However, they have the same numeric values as decimal literals - you are limited by the type you use. There isn't a special Hexa type.
If you have an integer and want to display is in hexadecimal base, you can use the x format (example):
int i = 255;
Console.Write(i.ToString("x")); // ff
Console.Write(i); // 255
Note that writing i = 0xff or i = 255 is exactly the same - the value is resolved by the compiler, and you get the same compiled code.
Lastly, if you have strings with hexadecimal numbers, you can convert them to integers, sum them, and reformat them (example):
string hexValue = "af";
int i = Convert.ToInt32(hexValue, 16); //175
2 Comments
:). I've added another answer.For 64 character numbers, you need to use the BigInteger type of .Net 4, the normal types are too small:
BigInteger bi1 = BigInteger.Parse("123456789012345678901234567890123456789012345678901234567890abc5", NumberStyles.HexNumber);
BigInteger bi2 = BigInteger.Parse("123456789012345678901234567890123456789012345678901234567890abc1", NumberStyles.HexNumber);
BigInteger sum = BigInteger.Add(bi1, bi2);
Console.WriteLine("{0:x}", sum); //or sum.ToString("x")
(remember adding a reference to System.Numerics)
3 Comments
You can use this code for sum your result. You can see more on my ByteConverters class
public static long HexLiteralToLong(string hex)
{
if (string.IsNullOrEmpty(hex)) throw new ArgumentException("hex");
int i = hex.Length > 1 && hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X') ? 2 : 0;
long value = 0;
while (i < hex.Length)
{
int x = hex[i++];
if
(x >= '0' && x <= '9') x = x - '0';
else if
(x >= 'A' && x <= 'F') x = (x - 'A') + 10;
else if
(x >= 'a' && x <= 'f') x = (x - 'a') + 10;
else
throw new ArgumentOutOfRangeException("hex");
value = 16 * value + x;
}
return value;
}
Usage :
var HexSum = HexLiteralToLong("FF") + HexLiteralToLong("FF");
Result :
510
Comments
On your last question: you can use hexadecimal constants in integer types (byte, short, int and long). In C# long is 64 bit, so longest hexadecimal constant is 0x1234567812345678 (or any other with 16 hexadecimal digits).
2 Comments
0x7fffffffffffffff: ideone.com/tdpIX , which is also visible in the specifications: msdn.microsoft.com/en-us/library/system.int64.maxvalue.aspx