user1903439
user1903439

Reputation: 2001

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?

Upvotes: 0

Views: 1037

Answers (2)

Ian Griffiths
Ian Griffiths

Reputation: 14537

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.

Upvotes: 1

TypeIA
TypeIA

Reputation: 17250

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.

Upvotes: 4

Related Questions