CSC209 Fall 2001 Karen Reid 1
C/C++ review – bits & bytes
(unsigned) char – 1 byte = 8 bits, (unsigned)
short int – 2 bytes = 16 bits, (unsigned) int – 4 bytes = 32 bits, float – 4 bytes, double – 8 bytes, pointer = 32 bits
No matter what the type, each is just a
sequence of bits (1s and 0s) in memory:
Eg: 01100001 = 97 = ‘a’ The left most bit is the “most significant bit”, the
right most the “least significant
Same bits, different interpretation
What is the value of 11111111 ? – it depends on the
type
Unsigned: 255 Signed: -1
Interpretation of signed & unsigned is the same as
long as most significant bit (msb) not set.
If msb (the sign bit) is set, then the value is
- negative. The value is given by:
- (value of msb) + (value of rest of bits)
So for 11111111: -(2^7) + (2^6+2^5+…+2^0) = -1 This is the two’s complement representation unsigned char uc = 255; char c = (char) uc; printf(“%d\n”,c)
A chart of values for a 4 bit integer
Bit value unsigned signed 0000 0 (0x0, 00) 0001 1 (0x1, 01) 1 0010 2 (0x2, 02) 2 0011 3 (0x3, 03) 3 0100 4 (0x4, 04) 4 0101 5 (0x5, 05) 5 0110 6 (0x6, 06) 6 0111 7 (0x7, 07) 7 1000 8 (0x8, 010)
- 8
1001 9 (0x9, 011)
- 7
1010 10 (0xA, 012)
- 6
1011 11 (0xB, 013)
- 5
1100 12 (0xC, 014)
- 4
1101 13 (0xD, 015)
- 3
1110 14 (0xE, 016)
- 2
1111 15 (0xf, 017)
- 1
Manipulate bits
Show 4 ways of turning on the 8th bit, using a
decimal integer, a hex value, an octal value, and a negative number: Unsigned char uc=0; uc = uc |
Questions like: do I give chmod() a decimal number or an
- ctal number – are irrelevant. You give chmod() the right