9
Bit Manipulations CS212

Bit Manipulations

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

Page 1: Bit Manipulations

Bit Manipulations

CS212

Page 2: Bit Manipulations

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

Page 3: Bit Manipulations

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

Page 4: Bit Manipulations

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

Page 5: Bit Manipulations

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

Page 6: Bit Manipulations

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

Page 7: Bit Manipulations

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

Page 8: Bit Manipulations

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

Page 9: Bit Manipulations

Complement

~ 0 1

1 0Used to flip all of the bits in a variable

unsigned char int1 = 0xaa; int1 = ~int1 // produces int1 = 0x55;