Arithmetic addition and subtraction on large hexadecimal strings - c#

How the arithmetic addition and subtraction can be carried out on large strings. For example, I have the following hexadecimal strings
string a1="B91EFEBFBDBDBFEFF39ABEE";
string a2="000FFFFFFFFFFFFFFFFFEEE";
then I want to do arithmetic addition a1+a2 to get the sum, not string concatenation.
And then arithmetic subtraction e.g. sum-a2 to get back string a1.
I tried to do
Int64 parseda1 = Int64.Parse(a1);
Int64 parseda2 = Int64.Parse(a2);
Int64 xyz = abc + abc;
MessageBox.Show(xyz.ToString("X"));// may be error in this as well
It trows exception, Input string was not in a correct format.

If you want really large numbers, you can use the BigInteger struct which represents an arbitrarily large signed integer. Try this:
string a1 = "B91EFEBFBDBDBFEFF39ABEE";
string a2 = "000FFFFFFFFFFFFFFFFFEEE";
BigInteger num1 = BigInteger.Parse(a1, NumberStyles.HexNumber);
BigInteger num2 = BigInteger.Parse(a2, NumberStyles.HexNumber);
BigInteger sum = num1 + num2;
Console.WriteLine(sum.ToString("X"));
Console.WriteLine((sum - num2).ToString("X")); //gets a1
Edit:
Looks like num1 gives us a negative number. That's probably not what you want. To fix that, read: MSDN: BigInteger.Parse Method
"If value is a hexadecimal string, the Parse(String, NumberStyles)
method interprets value as a negative number stored by using two's
complement representation if its first two hexadecimal digits are
greater than or equal to 0x80. In other words, the method interprets
the highest-order bit of the first byte in value as the sign bit. To
make sure that a hexadecimal string is correctly interpreted as a
positive number, the first digit in value must have a value of zero.
For example, the method interprets 0x80 as a negative value, but it
interprets either 0x080 or 0x0080 as a positive value."

Related

Will converting Char.GetNumericValue() to int destroy information?

I am implementing GetHashCode(). I want to sum the values in a property called string Id then divide
by some constant and return the result. I am using GetNumericValue():
int sum = 0;
foreach (var ch in Id)
sum += char.GetNumericValue(ch);
But it seems that GetNumericValue returns double. is it ok to convert it into an int?
I thought that Unicode characters are represented by whole number, why is double returned?
And is it okay to ignore it?
Why is double returned?
While 0-9 are the standard digits, actually there are some Unicode characters that represent numbers, some of them are floating point like ⅔ or ½. Let's get an example:
var ch = char.GetNumericValue('½');
Console.WriteLine(ch);// 0.5 output
Yes, it will lose data for some values, since this is the numerical value of unicode characters that are themselves numbers - and unicode includes characters that are non-integer numbers:
var val = char.GetNumericValue('½'); // or ¼, or ꠲, or ⳽
System.Console.WriteLine(val);

3 digit hexadecimal generator for Access Database

I am trying to figure out how to create a hexadecimal generator that always spits out 3 digits in C# and sends it to my access database. Here is the code that I found an example of on here and changed a little bit, but the generator sometimes only gives me 2 digits. What am I doing wrong?
Thank you,
var r = new Random();
int A = r.Next(100, 500);
string hexValue1 = A.ToString("X");
MessageBox.Show(hexValue1);
As described in
The Hexadecimal ("X") Format Specifier
The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.
So you can simply use
string hexValue1 = A.ToString("X3");
to always give you three digits (provided that A <= 0xFFF)..
The minimum possible value for a 3 digit hex value would be 0x100 (256 decimal) and the maximum value would be 0xFFF (4095 decimal). So in order to generate this string you need to use something like:
var r = new Random();
int A = r.Next(256, 4096); //Using the exclusive maximum (required max + 1)
string hexValue1 = A.ToString("X");
MessageBox.Show(hexValue1);

Invalid hex to decimal value

Attempting to convert hex to decimal but the below snippet is returning an incorrect value. Hex value is: BA51A114 and the expected results are: 3125911828.
string hex = "BA51A114";
MessageBox.Show(int.Parse(hex, System.Globalization.NumberStyles.HexNumber).ToString());
This is returning: -1169055468. When converted back to hex the value is now: FFFFFFFFBA51A114.
You're overflowing the bounds of an int by about a billion. You need to parse it as a long:
string hex = "BA51A114";
MessageBox.Show(long.Parse(hex, System.Globalization.NumberStyles.HexNumber).ToString());
Or as khlr points out, in this case a uint would also be sufficient. For another billion or so anyway...
You are over the int max value 2147483647

bitwise or a number in int form with a number in hex form

I have a number
int number = 509; // integer
string bool_number = Convert.ToString(number, 2); // same integer converted to binary no
I want to bitwise or this number with hex values 0x01, 0x02, 0x04 and 0x08.
(e.g. something like this)
result = number | 0x01
How can I do it? Should I convert number to hex form or whats the right way?
You can use hexadecimal values as numeric literals...
int number = 509;
int hexNumber = 0x02;
int newNumber = number | hexNumber;
// whatever
string newNumberAsBinaryString = Convert.ToString(newNumber, 2);
Console.WriteLine(newNumber);
// etc.
If you need to input a hex string and convert it to a numeric type:
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
If you need to output a numeric type as hex:
Console.WriteLine(num.ToString("x"));
// or
Console.WriteLine("{0:x}", num);
See also MSDN's page on dealing with hex strings.
An int value isn't in any particular base. You can use bitwise operators on an int at any time - there's no need to convert it first. For example:
int a = 509;
int b = 0x1fd;
The variables a and b have exactly the same value here. I happen to have used a decimal literal to initialize a, and a hex literal to initialize b, but the effect is precisely the same.
So you can bitwise OR your ints at any time. Your example (adding a suitable declaration and semicolon to make it compile):
int result = number | 0x01;
will work just fine - you don't need to do anything to prepare number for this sort of usage. (Incidentally, this will do nothing, because the result of a bitwise OR of the numbers 509 and 1 is 509. If you write 509 in binary you get 111111101 - the bottom bit is already 1, so ORing in 1 won't change anything.)
You should avoid thinking in terms of things like "hex values", because there isn't really any such thing in C#. Numeric bases are only relevant for numbers represented as strings, which typically means either literals in source code, or conversions done at runtime. For example, if your program accepts a number as a command line argument, then that will arrive as a string, so you'll need to know its base to convert it correctly to an int. But once it's an int it's just an int - there's no such thing as a hex value or a decimal value for an int.

Parsing a hexadecimal string to base 10 long integer

I need to parse a hexadecimal value to base 10 long integer. Value is something like:
9F2EEA4AA03D55B33172E9A86CFF6156AC1628C67983193A337B98995151F9B0F41562290DB98697280E805803E4B18914519CEB55CEA5D03A927C28C36A4BC7
How can i do this?
UPDATE:
In python, i used following:
>> num = "9F2EEA4AA03D55B33172E9A86CFF6156AC1628C67983193A337B98995151F9B0F41562290DB98697280E805803E4B18914519CEB55CEA5D03A927C28C36A4BC7"
>> int(num, 16)
>> 8337103942674051648235321365669510487642415361796636721089378763661406518267124809778145800381557738780272231500412167743930433352841689114003303823985607L
when my colleague tries #Sergey's answer, my colleague get a different result (a negative value while mine is not a negative one)
>> BigInteger bigInteger = BigInteger.Parse(num, NumberStyles.HexNumber);
>> -5070703987268545451338703632536335639836950458795756656634182680060357511806422167023728497785345688909759626686073883109823449459104880832430345182098489
Please take a look at BigInteger Structure to work with large integers.
BigInteger bigInteger = BigInteger.Parse("0D574F480A03D55B33172E9A86CFF6156AC1628C67983193A337B98995151F9B0F41562290DB98697280E805803E4B18914519CEB55CEA5D03A927C28C36A4BC7", NumberStyles.HexNumber);
string s = bigInteger.ToString(); // String with decimal representation.
Update
Prepend (start) the string with 0 if the number should be interpreted as positive even if its first character is 8–F. See the example above: 0D574...

Categories