Integers and their representation
All data in digital computers is stored as a sequence of bits,
with (modern) computers aggregating 8 bits to a byte.
An integer of a Pentium, for example, requires 4 bytes, or 32 bits.
Consider how these bits form bytes, and how integers are represented:
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/param.h>
static char *binary(unsigned int x)
{
#define NBITS ((sizeof x) * NBBY)
static char bits[NBITS+1];
char *b = bits;
for(int n=NBITS-1 ; n>=0 ; --n) {
*b = ((x & (1<<n)) ? '1' : '0');
++b;
}
*b = '\0';
return bits;
}
int main(int argc, char *argv[])
{
for(unsigned int x=0 ; x<=16 ; ++x) {
printf("%2u:", x); // in decimal, base 10
printf(" %s", binary(x)); // in binary, base 2
printf(" %08o", x); // in octal, base 8
printf(" 0x%04x", x); // in hexadecimal, base 16
printf("\n");
}
return 0;
}
|
|
Produces the output:
0: 00000000000000000000000000000000 00000000 0x0000
1: 00000000000000000000000000000001 00000001 0x0001
2: 00000000000000000000000000000010 00000002 0x0002
3: 00000000000000000000000000000011 00000003 0x0003
4: 00000000000000000000000000000100 00000004 0x0004
5: 00000000000000000000000000000101 00000005 0x0005
6: 00000000000000000000000000000110 00000006 0x0006
7: 00000000000000000000000000000111 00000007 0x0007
8: 00000000000000000000000000001000 00000010 0x0008
9: 00000000000000000000000000001001 00000011 0x0009
10: 00000000000000000000000000001010 00000012 0x000a
11: 00000000000000000000000000001011 00000013 0x000b
12: 00000000000000000000000000001100 00000014 0x000c
13: 00000000000000000000000000001101 00000015 0x000d
14: 00000000000000000000000000001110 00000016 0x000e
15: 00000000000000000000000000001111 00000017 0x000f
16: 00000000000000000000000000010000 00000020 0x0010
|
The constant NBBY is not a C99 symbol,
but operating systems provide it to give the
number of bits per byte.
|