COMP SCI 354 LECTURE 013

Bitwise Operations

Casting Review

1
2
3
// Type casting short to unsigned int
short x = 0xCFC7; // -12345
unsigned int y = (unsigned)x;

This code is doing (1) 2 bytes to 4 bytes (2) signed to unsigned.

So which comes first?

  • Size comes first: 0xCFC7 → 0xFFFF CFC7
  • Then signed to unsigned: Still 0xFFFF CFC7 which is 42945495
1
2
printf("x = %hX, x = %d \n", x, x);
printf("y = %dX, y = &u \n", y, y);

Default Casting

1
2
3
4
5
// -1 < 0 true
// -1 < 0U
// U makes the literal value into an unsigned number
// Signed type is converted to unsigned type by default
// So -1 < 0U is false

The endianness

1
2
3
4
5
6
7
int num = 0x87654321;
int *p = &num;
char *pc = (char *)p;

for (int i = 0; i < 4; i++) {
printf("%p: mem[%d] = %hhx \n", &pc[i], i, pc[i]);
}

Bitwise Operators

  • OR |
  • AND &
  • NOT ~
  • EX-OR ^
  • Left shift <<
  • Right shift >>: For signed number, it will shift 1s from left most; For unsigned number, it will shift 0s from the left most.

Applications

  1. Bit Masks

    Extract certain bits from a pattern (i. e. Extract the four least significant bits. Extract 0010 from 1001 0010, we can use&0000 1111 as a mask).

  2. Packed ints

    In Computer Graphics, red, green, blue and alpha(transparency) can be stored in a integer since each of them occupies 1 byte. The problem is how to get the value of blue. Also, we need shift certain bits and

  3. Bit Flags

    Bit flags are a very efficient way to store boolean data. Store multiple boolean data in an integer.

    Bit Operators as Bit Flags

  4. Multiplication & Division

    1
    2
    3
    4
    14 * 2 = 28
    0000 1110
    *2
    0001 1100

    multiplying by 2 is equal to left shift one bit in binary