how to add two Hexa strings in c#.net
how to add two Hexa strings in C#.net
string hex1="BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
string hex2="BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
i want to get decimal value by 开发者_高级运维adding these two hexa values.
int value = Convert.ToInt32(hexString1, 16) + Convert.ToInt32(hexString2, 16);
Given the length of your strings (32 characters) your numbers will not fit in a decimal let alone long or int. A solution for this would be to use the .Net 4 BigInteger data type. I cannot test it here but the code would look like this
BigInteger num1 = BigInteger.Parse("0" + hex1, NumberStyles.HexNumber);
BigInteger num2 = BigInteger.Parse("0" + hex2, NumberStyles.HexNumber);
BigInteger result = num1 + num2;
If you are not on .Net 4, you will have to use a data type that can store numbers of this magnitude e.g. double. Since a double has only 8 bytes your result will loose some precision.
EDIT
I tested it now. Turns out you have to set a reference to System.Numerics.dll and add a using statement for the namespace System.Numerics. Also if the numbers are positive you would have to prepend the strings with a "0" to prevent them from being parsed as negative numbers.
加载中,请稍侯......
精彩评论