change numeric base of negative numbers - c#

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

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

int.Parse not working

static void Main()
{
Console.Write("Please input a number: ");
Console.WriteLine("\n The number you selected was {0} \n", method());
}
static int method()
{
int var = int.Parse(Console.ReadLine());
return var;
}
The above code throws a format exception. I tried storing the input in a string variable and then parsing, but it had the same problem. I also tried using the Convert class and still had the same problem. I would appreciate if someone could show me where I am wrong.
I am trying to convert 23.4, for example. (It works for Natural numbers but why not 4345.5, for example)
23.4 is not an integer, so you cannot use int.Parse (or int.TryParse). Instead you have to parse it to a decimal number like decimal or double. You can use the TryParse methods like Double.TryParse to prevent an exception if it's not a valid number:
string input = Console.ReadLine();
double number;
if(double.TryParse(input.Trim(), out number))
{
// valid number
Console.WriteLine("\n The number you selected was {0} \n", number);
}
else
{
Console.WriteLine("Please enter a real number.");
}
Update from your comments i can see that you want to display an integer.
You can use (int)number to get an integer where the decimal part is simply truncated. If you want that it gets rounded use Math.Round first.
int integer = (int) number; // decimal part is truncated
integer = (int) Math.Round(number, 2, MidpointRounding.AwayFromZero); // rounded to two digits
If you just want to display a string without the decimal part you can also use format strings.
string numberString = number.ToString("N0");
You should be using double or float for rational numbers:
float num = float.Parse(Console.ReadLine())
You can return the integer part of your input string (3.6 becomes 3, for example) like this:
static int method()
{
float var = float.Parse(Console.ReadLine());
return (int)Math.Floor(var);
}
Integer32.Parse is for parsing 32 bit integers. It cannot parse numbers that cannot be represented as a 32 bit integer, such as 23.4, and it will throw an exception when it cannot parse the data. Use a different numeric representation if you wish to represent non-integer numbers.

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.

I need to take an int and convert it into its binary notation (C#)

I need to take an int and turn it into its byte form.
i.e. I need to take '1' and turn it into '00000001'
or '160' and turn it into '10100000'
Currently, I am using this
int x = 3;
string s = Convert.ToString(x, 2);
int b = int.Parse(s);
This is an awful way to do things, so I am looking for a better way.
Any Suggestions?
EDIT
Basically, I need to get a list of every number up to 256 in base-2. I'm going to store all the numbers in a list, and keep them in a table on my db.
UPDATE
I decided to keep the base-2 number as a string instead of parsing it back. Thanks for the help and sorry for the confusion!
If you need the byte form you should take a look at the BitConverter.GetBytes() method. It does not return a string, but an array of bytes.
The int is already a binary number. What exactly are you looking to do with the new integer? What you are doing is setting a base 10 number to a base 2 value. That's kind of confusing and I think you must be trying to do something that should happen a different way.
I don't know what you need at the end ... this may help:
Turn the int into an int array:
byte[] bytes = BitConverter.GetBytes(x);
Turn the int into a bit array:
BitArray bitArray = new BitArray(new[] {x});
You can use BitArray.
The code looks a bit clumsy, but that could be improved a bit.
int testValue = 160;
System.Collections.BitArray bitarray = new System.Collections.BitArray(new int[] { testValue });
var bitList = new List<bool>();
foreach (bool bit in bitarray)
bitList.Add(bit);
bitList.Reverse();
var base2 = 0;
foreach (bool bit in bitList)
{
base2 *= 10; // Shift one step left
if (bit)
base2++; // Add 1 last
}
Console.WriteLine(base2);
I think you are confusing the data type Integer with its textual representation.
int x = 3;
is the number three regardless of the representation (binary, decimal, hexadecimal, etc.)
When you parse the binary textual representation of an integer back to integer you are getting a different number. The framework assumes you are parsing the number represented in the decimal base and gives the corresponding integer.
You can try
int x = 1600;
string s = Convert.ToString(x, 2);
int b = int.Parse(s);
and it will throw an exception because the binary representation of 1600 interpreted as decimal
is too big to fit in an integer

Categories