c+ - Comment définissez-vous, clair, et basculez un peu

Mots clés : c++cbit-manipulationbitwise-operatorsc++c

meilleur 5 Réponses c+ - Comment définissez-vous, clair, et basculez un peu

vote vote

100

number |= 1UL << n; 
number &= ~(1UL << n); 
number ^= 1UL << n; 
bit = (number >> n) & 1U; 
number ^= (-x ^ number) & (1UL << n); 
number ^= (-(unsigned long)x ^ number) & (1UL << n); 
unsigned long newbit = !!x;    // Also booleanize to force 0 or 1 number ^= (-newbit ^ number) & (1UL << n); 
number = (number & ~(1UL << n)) | (x << n); 
vote vote

90

#include <bitset> #include <iostream>  int main() {     std::bitset<5> x;      x[1] = 1;     x[2] = 0;     // Note x[0-4]  valid      std::cout << x << std::endl; } 
[Alpha:] > ./a.out 00010 
vote vote

77

struct bits {     unsigned int a:1;     unsigned int b:1;     unsigned int c:1; };  struct bits mybits; 
mybits.b = 1; mybits.c = 0; 
mybits.a = !mybits.a; mybits.b = ~mybits.b; mybits.c ^= 1;  /* all work */ 
if (mybits.c)  //if mybits.c is non zero the next line below will execute 
vote vote

68

/* a=target variable, b=bit number to act upon 0-n */ #define BIT_SET(a,b) ((a) |= (1ULL<<(b))) #define BIT_CLEAR(a,b) ((a) &= ~(1ULL<<(b))) #define BIT_FLIP(a,b) ((a) ^= (1ULL<<(b))) #define BIT_CHECK(a,b) (!!((a) & (1ULL<<(b))))        // '!!' to make sure this returns 0 or 1  #define BITMASK_SET(x, mask) ((x) |= (mask)) #define BITMASK_CLEAR(x, mask) ((x) &= (~(mask))) #define BITMASK_FLIP(x, mask) ((x) ^= (mask)) #define BITMASK_CHECK_ALL(x, mask) (!(~(x) & (mask))) #define BITMASK_CHECK_ANY(x, mask) ((x) & (mask)) 
vote vote

52

enum ThingFlags = {   ThingMask  = 0x0000,   ThingFlag0 = 1 << 0,   ThingFlag1 = 1 << 1,   ThingError = 1 << 8, } 
thingstate |= ThingFlag1; thingstate &= ~ThingFlag0; if (thing & ThingError) {...} 

Questions similaires