Adding hexa values ​​in C #

On 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 maximum length of Hexa values ​​and which instance holds these values.

+4
source share
6 answers

For 64 character numbers you need to use the BigInteger .Net 4 type, the usual 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 link to System.Numerics )

+2
source

C # supports hexadecimal literals :

 int i = 0xff; 

However, they have the same numeric values ​​as decimal literals - you are limited to the type you use. There is no special type of Hexa .

If you have an integer and want to display it in a hexadecimal base, you can use the x format ( example ):

 int i = 255; Console.Write(i.ToString("x")); // ff Console.Write(i); // 255 

Please note that the entry i = 0xff or i = 255 exactly the same - the value is resolved by the compiler, and you get the same compiled code.

Finally, if you have strings with hexadecimal numbers, you can convert them to integers, sum them up and reformat them ( example ):

 string hexValue = "af"; int i = Convert.ToInt32(hexValue, 16); //175 
+14
source

Hexadecimal values ​​are simply old integers (after all, the number 10 in the base 10 and the number A in hexadecimal are the same thing, they are simply viewed in different ways); if you need to convert one to the sixth line, use: value.ToString("X") , where value is an integral type (for example, int ).

+1
source
  int a = 0x2; int b = 0x5f; int value = a + b; //adding hex values string maxHex = int.MaxValue.ToString("x"); //maximum range of hex value as int 
+1
source

In the last question, you can use hexadecimal constants in integer types (byte, short, internal and long). In C #, long is 64 bits, so the longest hexadecimal constant is 0x1234567812345678 (or any other with hexadecimal digits).

0
source

You can use this code to summarize your result. You can see more at the 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; } 

Using:

 var HexSum = HexLiteralToLong("FF") + HexLiteralToLong("FF"); 

Result:

 510 
0
source

Source: https://habr.com/ru/post/1332308/


All Articles