COMP SCI 354 LECTURE 013
Bitwise Operations
Casting Review
1 | // Type casting short to unsigned int |
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 | printf("x = %hX, x = %d \n", x, x); |
Default Casting
1 | // -1 < 0 true |
The endianness
1 | int num = 0x87654321; |
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
Bit Masks
Extract certain bits from a pattern (i. e. Extract the four least significant bits. Extract
0010
from1001 0010
, we can use&0000 1111
as a mask).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
Bit Flags
Bit flags are a very efficient way to store
boolean
data. Store multiple boolean data in an integer.Multiplication & Division
1
2
3
414 * 2 = 28
0000 1110
*2
0001 1100multiplying by 2 is equal to left shift one bit in binary