Graphics Programs Reference
In-Depth Information
only be in one of 2 32 possible bit combinations. This allows 32-bit signed
integers to range from −2,147,483,648 to 2,147,483,647. Essentially, one of
the bits is a flag marking the value positive or negative. Positively signed values
look the same as unsigned values, but negative numbers are stored differently
using a method called two's complement. Two's complement represents neg-
ative numbers in a form suited for binary adders—when a negative value in
two's complement is added to a positive number of the same magnitude, the
result will be 0. This is done by first writing the positive number in binary, then
inverting all the bits, and finally adding 1. It sounds strange, but it works and
allows negative numbers to be added in combination with positive numbers
using simple binary adders.
This can be explored quickly on a smaller scale using pcalc , a simple
programmer's calculator that displays results in decimal, hexadecimal, and
binary formats. For simplicity's sake, 8-bit numbers are used in this example.
reader@hacking:~/booksrc $ pcalc 0y01001001
73 0x49 0y1001001
reader@hacking:~/booksrc $ pcalc 0y10110110 + 1
183 0xb7 0y10110111
reader@hacking:~/booksrc $ pcalc 0y01001001 + 0y10110111
256 0x100 0y100000000
r eader@hacking:~/booksrc $
First, the binary value 01001001 is shown to be positive 73. Then all the
bits are flipped, and 1 is added to result in the two's complement representa-
tion for negative 73, 10110111. When these two values are added together,
the result of the original 8 bits is 0. The program pcalc shows the value 256
because it's not aware that we're only dealing with 8-bit values. In a binary
adder, that carry bit would just be thrown away because the end of the vari-
able's memory would have been reached. This example might shed some
light on how two's complement works its magic.
In C, variables can be declared as unsigned by simply prepending the
keyword unsigned to the declaration. An unsigned integer would be declared
with unsigned int . In addition, the size of numerical variables can be extended
or shortened by adding the keywords long or short . The actual sizes will vary
depending on the architecture the code is compiled for. The language of C
provides a macro called sizeof() that can determine the size of certain data
types. This works like a function that takes a data type as its input and returns
the size of a variable declared with that data type for the target architecture.
The datatype_sizes.c program explores the sizes of various data types, using
the sizeof() function.
datatype_sizes.c
#include <stdio.h>
int main() {
printf("The 'int' data type is\t\t %d bytes\n", sizeof(int));
Search WWH ::




Custom Search