This chapter introduces the bit operators and bit fields, and provides a review of decimal, binary, octal, and hexadecimal notation. The teaching objectives important to this material include:
Concepts:With C, you can manipulate the individual bits in a variable. Decimal numbers are written in base 10, while binary numbers are written in base 2. Octal numbers are written in base 8; hexadecimal numbers are written in base 16. A byte consists of 8 bits, with bit positions 0 to 7. Bit position 0 represents the low-order bit. Bit position 7 represents the high-order bit. The largest binary number that can be stored in an 8-bit byte is 255, which means one byte can represent 256 numbers (including zero). A signed int, can store numbers in the range -128 to +127, when the two's-complement method uses the 7th bit position to indicate positive or negative. The one's complement method forms the negative of a number by inverting each bit in the pattern. Binary fractions require two parts: a binary fraction and a binary exponent. The six bitwise operators and their meaning are:
Besides the bitwise operators, the five bitwise assignment operators are: &= |= ^= >>= <<= The usage of bitwise operators are several and include:
The formulas to remember for the bitwise shift operators are: number << n Multiplies number by 2 to the nth power number >> n Divides number by 2 to the nth power, if number is not negative A bit field is just a set of neighboring bits within an unsigned int, set up with a structure definition that labels each field and determines its width. The structure: struct { unsigned code1 : 2; unsigned code2 : 2; unsigned code3 : 8; } prcode; creates two 2-bit fields and one 8-bit field. Bit fields assist C programs in dealing with hardware matters. They often appear in implementation-dependent contexts. |