Bit Manipulations CS212
Bit Level Manipulators And (&) bitwise based on type Or ( | ) Xor ( ^ ) Compelment ( ~ ) Shift right ( >> ) no carry, in or out; based on type shift left ( << )
Bases other than 10 Binary ; base 2 ; ( 0,1) char myint = 0b00001111; // 1510 Octal ; base 8 ; (0,1,2,3,4,5,6,7) char myint2 = 0o017; // 1510 Hexadecimal ; base 16 ; (0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f) char myint3 = 0x0f ; // 1510
Shifting Logical shifts – shift in a 0 as pad character Arithmetic shifts – preserve the sign bit for right shift, act like a logical shift for left shift Rotate left – lsb becomes the msb Rotate right – msb becomes lsb In C and C++ : shifting an unsigned int acts as a logical shift shifting a signed int acts as an arithmetic shift rotates are not part of the language and must be done via a user provided function
Shifting unsigned char a; a = 0b00100010 << 2 ; // produces 0b1000 1000 unsigned char b; b = 0xaa >> 1; // b = 0x55 //turn on bit 5 mask = ( 1 << 5 );
And & 1 Used for masking or extracting bits in a variable or 1 Used for masking or extracting bits in a variable or testing the status of a bit or a field in a variable Also for turning bits off // check to see if bit 3 in int1 is set to 1 char int1 = 0xaa; char mask3 = 0b00001000; if ( int1 & mask3) printf(“bit 3 on”); else printf(“bit3 off); // turn bits 0 and 1 off in int4 char int4 = 0b10111011; char mask01 =0b11111100; int4 &=mask01 ; //result is int4 = 0b10111000; //clear a bit unsigned char b &= ~(1 << n);
Or | 1 Usually used for turning bits on // turn on bit 3 1 Usually used for turning bits on // turn on bit 3 char register = 0xaa; char bit3 = 0b00000100 ; register |= bit3; //register is now 0b10100100; // turn on bit n in a unsigned char a |= (1 << n);
Xor ^ 1 Called a half add or an add with no carry; can be used to flip bits // flip bit n in word unsigned char word ^= (1 << n); //set word to all zeros , xor it with itself word ^= word; //swap the values in a and b (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))
Complement ~ 1 Used to flip all of the bits in a variable 1 Used to flip all of the bits in a variable unsigned char int1 = 0xaa; int1 = ~int1 // produces int1 = 0x55;