Upload
belicia-romero
View
15
Download
0
Embed Size (px)
DESCRIPTION
Bit Manipulations. CS212. Bit Level Manipulators. And (&) bitwise based on type Or ( | ) bitwise based on type Xor ( ^ ) bitwise based on type Compelment ( ~ ) bitwise based on type Shift right ( >> ) no carry, in or out; based on type shift left (
Citation preview
Bit Manipulations
CS212
Bit Level Manipulators• And (&)
– bitwise based on type• Or ( | )
– bitwise based on type
• Xor ( ^ )– bitwise based on type
• Compelment ( ~ )– bitwise based on type
• Shift right ( >> )– no carry, in or out; based on type
• shift left ( << )– no carry, in or out; based on type
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
ShiftingLogical shifts – shift in a 0 as pad characterArithmetic shifts – preserve the sign bit for right shift, act like a logical shift for left shiftRotate left – lsb becomes the msbRotate 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
& 0 1
0 0 0
1 0 1
Used for masking or extracting bits in a variable or testing the status of a bit or a field in a variableAlso for turning bits off // check to see if bit 3 in int1 is set to 1char int1 = 0xaa; char mask3 = 0b00001000; if ( int1 & mask3) printf(“bit 3 on”); else printf(“bit3 off);
// turn bits 0 and 1 off in int4char int4 = 0b10111011; char mask01 =0b11111100;int4 &=mask01 ; //result is int4 = 0b10111000;
//clear a bitunsigned char b &= ~(1 << n);
Or
| 0 1
0 0 1
1 1 1
Usually used for turning bits on
// turn on bit 3char register = 0xaa; char bit3 = 0b00000100 ;register |= bit3; //register is now 0b10100100;
// turn on bit n in aunsigned char a |= (1 << n);
Xor
^ 0 1
0 0 1
1 1 0
Called a half add or an add with no carry; can be used to flip bits
// flip bit n in wordunsigned char word ^= (1 << n);
//set word to all zeros , xor it with itselfword ^= word;
//swap the values in a and b(((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))
Complement
~ 0 1
1 0Used to flip all of the bits in a variable
unsigned char int1 = 0xaa; int1 = ~int1 // produces int1 = 0x55;