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);
Related
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."
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.
I'm testing net xml serialization of double[] arrays so I'm interested to know whats the double value that has most characters int it's serialized for so I can test whats the max output size of serialized array.
It should be 24.
double.MinValue.ToString("R").Length
From double.ToString(string)
or "R", which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision.
you have that there are at max 17 digits, plus 1 for sign, plus 1 for the decimal separator, plus 5 for the E+xxx (double.MaxValue is 1.7976931348623157E+308 and double.Epsilon, the smallest value > 0, is 4.94065645841247E-324, so both in the form E[+-][0-9]{1,3}).
Note that technically, in some strange languages,
var str2 = double.PositiveInfinity.ToString("R");
could be longer (because the string is localized), but I hope you'll serialize your numbers with CultureInfo.InvariantCulture!
But remember that users could have changed their culture from the control panel... something like:
var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NegativeSign = "Negative";
culture.NumberFormat.NumberDecimalSeparator = "DecimalSeparator";
var str4 = double.MinValue.ToString("R", culture);
Result: Negative1DecimalSeparator7976931348623157E+308
For this reason it's better to use the CultureInfo.InvariantCulture :-)
But if you want to know the truth, in the Control Panel the decimal separator can be long up to 3 characters, and the negative sign up to 4 (you can try it, or you can check the LOCALE_SDECIMAL and LOCALE_SNEGATIVESIGN, clearly the terminating null character can be ignored in .NET)
You can try -1.0 / 3.0, it will have many decimals.
How do I replace the decimal part of currency with 0's
Here's my cuurency: 166.7
This is to be formatted as 000000016670
The length of this field is 12.
s.padright(12,0); This is will the second part I believe.
The first part will involve replace the number after the decimal with 000..
Thanks
You can multiply by 100 then format the number.
var num = 166.7;
var numString = (num * 100).ToString("000000000000");
Multiplying by 100 turns 166.7 to 16670. Next you need to pad the left part of the number, which is what the ToString does. Each 0 represents a digit. It means, write the number that belongs to that digit, and if no number is present print 0.
How to convert a negative decimal number to a hexadecimal one?
I know how to convert positive numbers from one base to another.
The widows calculator returns a huge number something like FFFFFFFFFFFFCFC7 in hex for -12345 in dec.The value that I need to process further more is CFC7, but I don't know how to get it using C#.
Not exactly sure if that is what you need:
int i = -12345;
string test = i.ToString("X"); // test will hold: "FFFFCFC7"
int HexI = Convert.ToInt32(test, 16); // HexI will hold: -12345
Try this:
int decimalValue = -12345;
string hexVal = String.Format("{0:x2}", decimalValue);