Set integer value as bitmask

What is the easiest way to assign an integer value to a bitmask? For example, I want an integer with the first, third and fourth bits = 1, the other = 0.

Of course I'm looking for code, not for a single value! And, of course, there are many possibilities, but I try to find the simplest and most descriptive look

+3
source share
6 answers

I think the best way to think (!) Is to simply index the bits from 0, and then apply "to set n: th bits, a bitwise OR with a value (1 <n)):

int first_third_and_fourth = (1 << 0) | (1 << 2) | (1 << 3);
+7
source

If you want your code to be read in terms of bit numbers, something like this might 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;

, , :

int mask = 0x000d;
+7

OR Bitwise (|) :

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

, (&):

int isset = x&FIRST_BIT;
+2

:

int x = 0x0D;

gcc :

int x = 0b1101;
+1
0
source

Do

int something = 0x00000001 * 2;

until you get where you want.

0
source

Source: https://habr.com/ru/post/1746560/


All Articles