Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding hexa values in C#

Tags:

c#

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.

like image 315
Hset Hset Aung Avatar asked Dec 16 '10 05:12

Hset Hset Aung


People also ask

Can you use hex in C?

In C programming language, we can use hexadecimal literals in any expressions; we can assign hexadecimal numbers to the variables. To use hexadecimal literals, we use 0X or 0x as a prefix with the number. For example 0x10 is a hexadecimal number, which is equivalent to 16 in the decimal number system.

How do you store a hex value in a variable?

To assign value in hexadecimal format to a variable, we use 0x or 0X suffix. It tells to the compiler that the value (suffixed with 0x or 0X) is a hexadecimal value and assigns it to the variable.

What is 0x in C?

In C and languages based on the C syntax, the prefix 0x means hexadecimal (base 16).


3 Answers

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)

like image 119
Kobi Avatar answered Oct 13 '22 12:10

Kobi


  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
like image 2
Javed Akram Avatar answered Oct 13 '22 12:10

Javed Akram


Hexadecimal values are just plain old integers (after all, the number 10 in base ten and the number A in hexadecimal are the same thing, just viewed differently); if you need to convert one to a hex string, use: value.ToString("X"), where value is an integral type (like int).

like image 1
user541686 Avatar answered Oct 13 '22 13:10

user541686