Presentation is loading. Please wait.

Presentation is loading. Please wait.

Bit Manipulations CS212.

Similar presentations


Presentation on theme: "Bit Manipulations CS212."— Presentation transcript:

1 Bit Manipulations CS212

2 Bit Level Manipulators
And (&) bitwise based on type Or ( | ) Xor ( ^ ) Compelment ( ~ ) Shift right ( >> ) no carry, in or out; based on type shift left ( << )

3 Bases other than 10 Binary ; base 2 ; ( 0,1)
char myint = 0b ; // 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

4 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

5 Shifting unsigned char a; a = 0b << 2 ; // produces 0b unsigned char b; b = 0xaa >> 1; // b = 0x55 //turn on bit 5 mask = ( 1 << 5 );

6 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 = 0b ; if ( int1 & mask3) printf(“bit 3 on”); else printf(“bit3 off); // turn bits 0 and 1 off in int4 char int4 = 0b ; char mask01 =0b ; int4 &=mask01 ; //result is int4 = 0b ; //clear a bit unsigned char b &= ~(1 << n);

7 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 = 0b ; register |= bit3; //register is now 0b ; // turn on bit n in a unsigned char a |= (1 << n);

8 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)))

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


Download ppt "Bit Manipulations CS212."

Similar presentations


Ads by Google