Programming in C

(Barry) #1

280 Chapter 12 Operations on Bits


To convert a negative number from binary back to decimal, first complement all of
the bits, convert the result to decimal, change the sign of the result, and then subtract 1.
Given this discussion about twos complement representation, the largest positive
number that can be stored into nbits is 2n–1–1. So in eight bits, you can store a value up
to 2^7 – 1, or 127. Similarly, the smallest negative number that can be stored into nbits is
–2n–1, which in an eight-bit byte comes to –128. (Can you figure out why the largest
positive and smallest negative values are not of the same magnitude?)
On most of today’s processors, integers occupy four contiguous bytes, or 32 bits, in
the computer’s memory.The largest positive value that can, therefore, be stored into such
an integer is 2^31 –1 or 2,147,483,647, whereas the smallest negative number that can be
stored is –2,147,483,648.
In Chapter 4, “Variables, Data Types, and Arithmetic Expressions,” you were intro-
duced to the unsignedmodifier and learned that it could be used to effectively increase
the range of a variable.This is because the leftmost bit is no longer needed to store the
sign of the number because you are only dealing with positive integers.This “extra” bit is
used to increase the magnitude of the value stored in that variable by a factor of 2. More
precisely,nbits can now be used to store values up to 2 n–1. On a machine that stores
integers in 32 bits, this means that unsigned integers can range in value from 0 through
4,294,967,296.

Bit Operators


Now that you have learned some preliminaries, it’s time to discuss the various bit opera-
tors that are available.The operators that C provides for manipulating bits are presented
in Table 12.1.

Ta b le 12.1 Bit Operators
Symbol Operation
& Bitwise AND
| Bitwise Inclusive-OR
^ Bitwise Exclusive-OR
~ Ones complement
<< Left shift
>> Right shift

All the operators listed in Table 12.1, with the exception of the ones complement opera-
tor ~,are binary operators and as such take two operands. Bit operations can be per-
formed on any type of integer value in C—be it short,long,long long,and signedor
unsigned—and on characters, but cannot be performed on floating-point values.
Free download pdf