Unformatted text preview:

Slide 1Slide 2Slide 3Slide 4Slide 5Slide 6Slide 7Slide 820. LOW-LEVEL PROGRAMMINGBitwise Shift Operators• The bitwise shift operators are:<< left shift>> right shift• The expression i << j represents i shifted left j positions, zero-filled.• The expression i >> j represents i shifted right j positions. If i is of an unsigned type or if the value of i is not negative, then zero bits are added at the left as needed. If i is negative, the result depends on the implementation.Bitwise Shift Operators• For portability, it’s best to perform shifts only on unsigned numbers.• Examples:unsigned short int i, j;i = 13; /* i is now 13 (binary 0000000000001101) */j = i << 2; /* j is now 52 (binary 0000000000110100) */j = i >> 2; /* j is now 3 (binary 0000000000000011) */Other Bitwise Operators• The other bitwise operators are:~ bitwise not& bitwise and^ bitwise xor| bitwise orOther Bitwise Operators• Examples:unsigned short int i, j, k;i = 21; /* i is now 21 (binary 0000000000010101) */j = 56; /* j is now 56 (binary 0000000000111000) */k = ~i; /* k is now 65514 (binary 1111111111101010) */k = i & j; /* k is now 16 (binary 0000000000010000) */k = i ^ j; /* k is now 45 (binary 0000000000101101) */k = i | j; /* k is now 61 (binary 0000000000111101) */• Warning: Don’t confuse the bitwise operators & and | with the logical operators && and ||.Using the Bitwise Operators to Access Bits• Setting a bit. To set a bit, use a “mask” that contains a 1 bit in the desired position:i |= 0x0010; /* sets bit 4 */If the position of the bit is stored in a variable, use a shift operator to create themask:i |= 1 << j; /* sets bit j */Using the Bitwise Operators to Access Bits• Clearing a bit. To clear a bit, use a mask that contains a 0 bit in the position to be cleared:i &= 0xffef; /* clears bit 4 */An alternative:i &= ~ 0x0010; /* clears bit 4 */The latter form is particularly useful if the position of the bit is stored in a variable:i &= ~ (1 << j); /* clears bit j */Using the Bitwise Operators to Access Bits• Testing a bit. Testing a bit requires a mask containing a 1 bit:if (i & 0x0010) … /* tests bit 4 */To test whether bit j is set, use the following statement:if (i & 1 << j) … /* tests bit j


View Full Document

UF CGS 3460 - LOW-LEVEL PROGRAMMING

Download LOW-LEVEL PROGRAMMING
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view LOW-LEVEL PROGRAMMING and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view LOW-LEVEL PROGRAMMING 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?