Joseph Haugh
University of New Mexico
!0x00 == 0x01 and not 0x11?
! is a logical operator! to 0 (false) is 1 (true)~ to 0 (assuming 32 bits) is FFFFFFFF in hex&) and the operator & (as give me the address of)?NAND operator?Shift/AND commonly used to extract subset of bits from integral types
int x, y, z;
// Pull bits 16-23 out of X
y = (x >> 16) & 0xff;OR and shift used to assemble multiple values into a single larger value
// Construct z out of those bits and another value;
z = (y & 0xff) | ((0x18 << 8) & 0x3f00);Used in places where you pack multiple values into a single word (e.g. device drivers)
C unions, structs, and bit-fields are another way to do this (more later)
~)0111) would become -7 (1000)000) becomes -0 (111)011) + -3 (100)?111, -0011) + -1 (110)?10011 back to the least significant 3 bits to get 0103-bit one’s-complement:
| Bits | Unsigned Value | One’s Complement Value |
|---|---|---|
| 000 | 0 | 0 |
| 001 | 1 | 1 |
| 010 | 2 | 2 |
| 011 | 3 | 3 |
| 100 | 4 | -3 |
| 101 | 5 | -2 |
| 110 | 6 | -1 |
| 111 | 7 | -0 |
011100101000011110000011) + -3 (101) = 00003-bit two’s-complement:
| Bits | Unsigned Value | Two’s Complement Value |
|---|---|---|
| 000 | 0 | 0 |
| 001 | 1 | 1 |
| 010 | 2 | 2 |
| 011 | 3 | 3 |
| 100 | 4 | -4 |
| 101 | 5 | -3 |
| 110 | 6 | -2 |
| 111 | 7 | -1 |
Converting base 2 to base 10 (X = binary number, w = word size):
C short is 2 bytes long
| Decimal | Hex | Binary | |
|---|---|---|---|
| x | 15213 | 3B 6D | 00111011 01101101 |
| y | -15213 | C4 93 | 11000100 10010011 |
00001101 = 1 * 23 + 1 * 22 + 1 * 20 = 131000001101 = 1 * 23 + 1 * 22 + 1 * 20 = 131011110011 = −1 * 27 + 1 * 26 + 1 * 25 + 1 * 24 + 1 * 21 + 1 * 20 = −131000001101 = 1 * 23 + 1 * 22 + 1 * 20 = 131011110011 = −1 * 27 + 1 * 26 + 1 * 25 + 1 * 24 + 1 * 21 + 1 * 20 = −131000001101 + 11110011 = 00000000Converting −1310 to 2’s complement:
Convert absolute value to binary: 1310 = 00001101
Invert all the bits: 11110010
Add 1: 11110011
Verify, recall $TB2D(X) = -x_{w-1} * 2^{w-1} + \sum_{i=0}^{w-2} x_i * 2^i$:
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | |
|---|---|---|---|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 0 | 0 | 1 | 1 | |
| -128 | 64 | 32 | 16 | 0 | 0 | 2 | 1 | = −1310 |
| Decimal | Hex | Binary | |
|---|---|---|---|
| UMAX | 65535 | FF FF | 11111111 11111111 |
| TMAX | 32767 | 7F FF | 01111111 11111111 |
| TMIN | -32768 | 80 00 | 10000000 00000000 |
| -1 | -1 | FF FF | 11111111 11111111 |
| 0 | 0 | 00 00 | 00000000 00000000 |
ULONG_MAXLONG_MAXLONG_MIN