set integer value as bit mask
What is simplest way to assign a bit mask to integer value? For example I want integer with first, third and forth bits = 1, other = 0.
Certainly I am looking for code, not for single value! And certainly there lot of possibilities, but I try t开发者_C百科o find simplest and most descriptive looking
I think the best way to think (!) is to just index bits from 0, and then apply "to set the n:th bit, bitwise-OR with the value (1 << n)":
int first_third_and_fourth = (1 << 0) | (1 << 2) | (1 << 3);
If you want your code to be readable in terms of the bit numbers, something like this may be useful:
#define b0 0x0001
#define b1 0x0002
#define b2 0x0004
#define b3 0x0008
#define b4 0x0010
:
#define b15 0x8000
int mask = b3|b2|b0;
But, after a while you should be able to tell which hex values relate to which bits and you won't need mnemonic tricks like that:
int mask = 0x000d;
Use the OR Bitwise operator (|
) to combine bits:
#define FIRST_BIT (0x1)
#define SECOND_BIT (0x2)
#define THIRD_BIT (0x4)
#define FOURTH_BIT (0x8)
/* Increase by for each bit, *2 each time,
0x prefix means they're specified via a hex value */
int x = FIRST_BIT | THIRD_BIT | FOURTH_BIT;
And you can check if a bit is set using the AND Bitwise operator (&
):
int isset = x&FIRST_BIT;
This should do it:
int x = 0x0D;
And if you're lucky enough to use gcc and don't need to be portable:
int x = 0b1101;
Here is an online bit converter, if you don't want to do the sum yourself:
http://www.binaryconvert.com/convert_unsigned_int.html
Just fill in the bits below (e.g. 1101), and compute the answer (e.g. 0x0000000D). Any capable calculator should be able to do the same ...
Do
int something = 0x00000001 * 2;
until you get to where you want.
精彩评论