Invalid hex to decimal value - c#

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

Related

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);

Arithmetic addition and subtraction on large hexadecimal strings

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."

Converting string to sortable number

Is there any way of converting a string value (any content) to a number such that they both sort in the same way? I don't need to be able to convert the number back to a string. In fact it would be an advantage if it were impossible to convert it back.
I don't need to be able to sort any length of string. If a 64-bit long integer is used as the sort-value then I could trim the texts to a value that fits this number range.
I don't think there can be 100% correct way since sorting a string depends on the culture. For ex
int c1 = String.Compare("AA", "BB", false, CultureInfo.GetCultureInfo("en-US")); //return -1
int c2 = String.Compare("AA", "BB", false, CultureInfo.GetCultureInfo("da-DK")); //return 1
The closest thing I can think of is:
ulong l = BitConverter.ToUInt64(Encoding.UTF8.GetBytes(str), 0);
PS: pad str if its len is shorter than 8
You could take the first 8 bytes from the string, the 8 bytes would make up a ulong. It would only be 4 characters of the string with unicode, or 8 characters if you limit the strings to ASCII.

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.

How to convert an integer to fixed length hex string in C#?

I have an integer variable with max value of 9999.
I can convert to fixed length string (4-characters):
value.ToString("0000");
and I can convert it to hex:
value.ToString("X");
I want to convert it to a hex string of four characters (padded with 0 at the left if the value is converted to less than four digits hex value). I tried the following which didn't work.
value.ToString("0000:X");
OK, I can check the length of hex string and pad left with zeros.
But is there any straightforward way?
Use a number after the X format specifier to specify the left padding : value.ToString("X4")
String.Format( "{0:X2}", intValue)
Here is another method,
You can define a function and pass it 2 values, one the actual number and the second is the max length to fix.
i.e.
public string FixZero(string str, int maxlength)
{
string zero = "000000000000000000000000000000000000000";
int length = str.Length;
int diff = maxlength- length;
string z = zero.Substring(1, diff);
z = z + str;
return z;
}
you need integers in the format 0012, FixZero("12", 4)
or for 0001234, FixZero("1234", 7)

Categories