2. Data Representation
Part of
CS:2630, Computer Organization Notes

When we write computer programs, we always deal with representations. For example, we don't deal with text the way a calligrapher or author deals with text, we deal with a specific character set that may be used to represent text. Instead of dealing with integers or real numbers, we deal with finite precision representations of integers and we deal with floating point numbers.
Well designed programming languages allow the programmer to treat these representations as if they were identical to the abstractions they represent, but this identity is never complete. Thus, for example, our machine representations of integers behave exactly like abstract integers until a result greater than the machine precision is produced; at that point, either the behavior of integer variables becomes very strange (the usual consequence in C and C++) or the program raises an exception (the usual consequence in Java).
If speed is no issue, arbitrary precision arithmetic packages are available in some languages such as C and Java. These packages, while slow, automatically switch to larger representations every time the result of a computation overflows the representation previously in use. In languages where speed is of only secondary importance, such as Python, all integers are represented with such arbitrary precision packages.
Just about every introduction to assembly language or machine language programming ever written begins with a section like this. The IBM 7040/7044 Data Processing System Student Text (IBM, 1963) begins with with a chapter on binary arithmetic that is as good as anything more recent, and the Introduction to Programming for the PDP8 (DEC, 1973) has a nice "Number System Primer" that covers this ground equally well!
All modern computers use binary representations for their data, and all use fixed size containers for data. There is no reason that computers could not be built that use other representations; "trinary" (base 3) logic devices aren't hard to build, and in fact, decimal computers were built in large numbers in the 1960s. There is no compelling benefit to using nonbinary representations, though, and even the decimal machines of the 1960s were built using binary logic and used binarycodeddecimal (BCD) internally.
The bit is the fundamental unit of information. A bit has two values, conventionally called zero or one. We could as easily name the values on and off, high and low, or true and false; in fact, all of those names are used in different contexts, and the truth is that all such names are arbitrary. The representation of a bit inside the computer is also arbitrary. The presence or absence of holes in a punched card or strip of paper tape was once a common representation of bits, while inside the computers, the two values of a bit are usually represented using different voltages. The specific voltages used does not generally matter to the computer architect, but is left to the engineering level in the design.
Binary encoding of information dates back to the 19^{th} century with the development of the punched card, but it only grew to maturity in the second half of the 20^{th} century, with the dawn of the computer age. Over the years, bits have been grouped in many different ways, and these groupings have been given many names, words, bytes, characters and octets are but a few examples.
An assembly language is a language for assembling data and instructions into memory. The most primitive operations in an assembly language place individual data items such as bytes, words or halfwords into memory. Other more complex operations fill memory with instructions; initially, we will ignore these.
In most assembly languages, each line of text specifies one data item of some kind to be placed in memory. Consecutive lines of text specify the contents of consecutive memory locations. The assembly directive or instruction on each line specifies how to place data in memory, while the operands of the directive or instruction specify what data to place in memory.
Our assembly language is called SMAL, because it is a Symbolic Macro Assembly Language. The central purpose of any assembly language is to assemble data into memory. SMAL contains direct support for 8bit bytes, 16bit halfwords and 32bit words, using the B, H and W directives. (There is also a T directive for the sometimes useful 24bit triplebyte quantity.) Each of these assembly directives takes an operand giving the value of one byte, halfword or word. One word of memory can be filled with a W directive, or with two consecutive H directives, or four B directives. (Or, more obscurely, a T and then a B directive.)
W 2#10101010110011001111000011111111 H 2#1111000011111111 H 2#1010101011001100 B 2#11111111 B 2#11110000 B 2#11001100 B 2#10101010 
In this example, we have filled 3 words of memory so that each 32bit word holds the identical binary value. The first line of code assembles a word as a single operation. The next 2 lines assemble the 2 halfwords of a word in 2 operations, while the final 4 lines assemble the 4 bytes of a word in 4 separate operations.
The values in this example were all given in binary, indicated by the leading 2# on each word. The SMAL assembler supports other data representations, to be discussed later. When assembling code for the Hawk or for the Intel 8086/Pentium family, the least significant byte or halfword is always assembled first. Some other computers, notably the IBM Power architecture, put the most significant byte first when breaking a word down into multiple bytes. There is no particular advantage of one scheme over the other, so different computers take one or the other approach at random. This variety can be a source of confusion for novice programmers.
How many values can be coded in one bit? Two! We'll call them 0 and 1 for now, but in other contexts, it makes more sense to call them true and false. The names we use are arbitrary. How many values can be coded by 2 bits? By 3 bits? By 4 bits? Here is a systematic listing of all possible combinations of 4 bits:
0 0 0 0  1 0 0 0  4 bits gives 2^{4} = 16 possibilities 
0 0 0 1  1 0 0 1  
0 0 1 0  1 0 1 0  
0 0 1 1  1 0 1 1  
0 1 0 0  1 1 0 0  
0 1 0 1  1 1 0 1  
0 1 1 0  1 1 1 0  
0 1 1 1  1 1 1 1 
The above table lists of all combinations of 2 bits, in the rightmost 2 bits of each quadrant, and all combinations of 3 bits in the rightmost 3 bits of each column. In general, to represent n distinct values, it takes ⌈log_{2}(n)⌉ bits (log_{2} is the logarithm to the base 2; ⌈i⌉ means i rounded up to the next integer).
How we associate values with bit combinations is our business. We could represent Tuesday as 0000 and five as 0001, or we could be systematic, associating 0000 with a, 0001 with b, and so on. The need for compatibility with older encodings frequently prevents use of rational systematic encodings. Character encodings can be very arbitrary. Consider the character set used by ILLIAC I, a computer built at the University of Illinois in the 1940s. Despite the early date, this character set inherits its odd order from even older technology. The table below was transcribed from a typewritten original in The ILLIAC Miniature Manual by John Halton (U. of Illinois Digital Computer Lab file no 260, Oct 22 1958, page 3):
 Characters n for 92 Tape Holes  F/S L/S  Orders  o 0 P 2F o O 1 Q 66F o O 2 W 130F o OO 3 E 194F oO 4 R 258F oO O 5 T 322F oOO 6 Y 386F oOOO 7 U 450F Oo 8 I 514F Oo O 9 O 578F Oo O + K 642F Oo OO  S 706F OoO N N 770F OoO O J J 834F OoOO F F 898F OoOOO L L 962F 
 Characters n for 92 Tape Holes  F/S L/S  Orders  O o Delay Delay 3F O o O $(Tab) D 67F O o O CR/LF CR/LF 131F O o OO ( B 195F O oO L/S=LetterShift 259F O oO O , V 323F O oOO ) A 387F O oOOO / X 451F OOo Delay Delay 515F OOo O = G 579F OOo O . M 643F OOo OO F/S=FigureShift 707F OOoO ' H 771F OOoO O : C 835F OOoOO x Z 899F OOoOOO Space Space 963F 
This character set is coded using
5 bits per character, with two special codes, L/S
or letter shift and F/S or figure shift used to
shift between the two different and wildly disorganized sets of 32 characters.
The code CR/LF or carriage return  line feed was used to
mark the end of each text line.
In the table, the letters O and o are used to signify
holes punched in the paper tape that the ILLIAC I system used for input and
output. These tapes could be punched or printed using Teletype machines.

The jumbled organization of this character code is based in part on the QWERTY layout of the keys on a typewriter keyboard, but beyond that, it is something of a a mystery! The tape is punched with a hole for each one in the binary code, while no hole stands for the digit zero. The row of smaller holes punched along the tape does not code any data; these holes engate the sprocket that pulls the tape through the tape reader. In reading the characters from the tape, the sprocket holes serve somewhat like a decimal point.
Exercises:
a) Show the string "HELLO WORLD." as it would have been punched on paper tape for the ILLIAC I. Remember, you don't know if the previous text left the system in figureshift or lettershift state. (Type capital O for data holes in the tape, use small o for sprocket holes.)
b) What is encoded on the snippet of ILLIAC I tape given above?
The ASCII character set was proposed in the early 1960s as a sensible response to the limits of the 6bit character sets common at the time. ASCII (the American Standard Code for Information Interchange, later called ISO7) was intended for use on new computers with 8bit bytes, but it only used 7 bits and it had an uppercase only subset that fit in 6 bits:
left 3 bits  

000  001  010  011  100  101  110  111  
Right 4 bits  0000  NUL  DLE  SP  0  @  P  `  p  
0001  SOH  DC1  !  1  A  Q  a  q  
0010  STX  DC2  "  2  B  R  b  r  
0011  ETX  DC3  #  3  C  S  c  s  
0100  EOT  DC4  $  4  D  T  d  t  
0101  ENQ  NAK  %  5  E  U  e  u  
0110  ACK  SYN  &  6  F  V  f  v  
0111  BEL  ETB  '  7  G  W  g  w  
1000  BS  CAN  (  8  H  X  h  x  
1001  HT  EM  )  9  I  Y  i  y  
1010  LF  SUB  *  :  J  Z  j  z  
1011  VT  ESC  +  ;  K  [  k  {  
1100  FF  FS  ,  <  L  \  l    
1101  CR  GS    =  M  ]  m  }  
1110  SO  RS  .  >  N  ^  n  ~  
1111  SI  US  /  ?  O  _  o  DEL 
Spaces are encoded with the SP code, 010 0000.
The function of the other named codes will
be given later. Using this, we can encode the string
"Hello World!" in ASCII as follows:
100 1000  H  101 0111  W  
110 0101  e  110 1111  o  
110 1100  l  111 0010  r  
110 1100  l  110 1100  l  
110 1111  o  110 0100  d  
010 0000  010 0001  ! 
The ASCII character set, now officially known as the ISO7 Latin 1 character set, is the basis of the widely used character sets in common use today and forms the base from which Unicode was developed. From the very start, ASCII text has been encoded in 8 bit bytes by adding an extra bit on the left, so the letter 'a' is coded as either 0110 0001 or 1110 0001 instead of being coded as 110 0001. Some vendors opted to set the extra bit to 0 while others set it to 1. Fortunately this variation ended in the 1980s. In all modern 8bit character sets, this bit is zero to indicate the classic ASCII character set and one to indicate one or another extended character set.
Pure Unicode uses 21 bits to encode each
character, although the characters from the common alphabets of the world
can be coded using the 16bit subset of Unicode.
When Unicode is represented in the UTF8 encoding, the binary codes
0000 0000 to 0111 1111 are used for the 128 characters of the
classic ASCII character set. Each of the
Unicode codes from 128 to 2047 can be coded in twobytes in UTF8.
The twobyte UTF8 codes include complete support for
the Latin, Cyrillic, Greek, Arabic and Hebrew alphabets, including a wide
range of accent marks. For codes from 2048 to 65535, the UTF8 encoding
uses three bytes per character.
These three byte codes suffice for most purposes, but the UTF8 extension
scheme can be continued to encode up to 36 bits of data as a string of seven
8bit bytes. The Unicode standard never needs more than 4 bytes to encode a
21bit value in UTF8.
Range of Values  Encoding  Number of Bytes  

0    127  0xxx xxxx  1 (classic ASCII)  
128    2047  110x xxxx  10xx xxxx  2  
2048    65535  1110 xxxx  10xx xxxx  10xx xxxx  3 
In the UTF8 scheme illustrated above, the each bit of the pure Unicode character is shown as an x, while bits added in the UTF8 encoding are given explicitly as ones and zeros. The order of the Unicode bits remains unchanged when the consecutive bytes of the UTF8 encoding are written out from left to right.
Note that not all possible 21bit values are legal Unicode characters. We will not cover the full complexity here, but it is worth noting that UTF16 allows all valid Unicode characters to be represented in 1 or 2 consecutive 16bit words, with most characters in the common alphabets represented in just 1 word.
One other character set from the 1960s is still with us, EBCDIC, the Extended Binary Coded Decimal Interchange Code. This is an 8bit character set originally devised by IBM and still used on the IBM enterprise servers used by many large corporations. EBCDIC, extends BCD, an older 6bit code.
Whether ancient or modern, all practical character codes contain several nonprinting codes. In ASCII, these have standard 2 and 3 letter names. Except for space, SP, these are known as control characters. Most ASCII control characters are rarely used. In some cases, they were included in ASCII to support applications that are now obsolete and some of them were included to support applications that never caught on. In the C programming language and its relatives, special representations are used for several control characteres. For example, HT (horizontal tab) is represented with \t and FF (form feed) with \f.
NUL  null, intended to be ignored, commonly abused as endofstring  

SOH  start of heading  
STX  start of text  
ETX  end of of text  
EOT  end of of transmission  
ENQ  enquire (about the status of a remote terminal?)  
ACK  acknowledge (an answer to ENQ?)  
BEL  \b  bell, used to ring the bell in the remote terminal 
BS  backspace, commonly abused as erase  
HT  \t  horizontal tab, still used as originally intended 
VT  vertiacal tab, commonly used as a reverse linefeed  
LF  \n  linefeed, frequently used as endofline 
FF  \f  formfeed, on printers, frequently causes page eject 
CR  \r  carriage return, frequently used to mean enter 
SO  shift out (change text color?)  
SI  shift in (undo SO)  
DLE  data link escape  
DC1  device control 1 (for devices on a remote terminal)  
DC2  device control 2  
DC3  device control 3  
DC4  device control 4  
NAK  negative acknowledge (an answer to ENQ?)  
SYN  synchronize (for synchronous data links)  
ETB  end transmission block  
CAN  cancel  
EM  end of message  
SUB  substitute  
ESC  escape (a prefix altering the use of what follows)  
FS  file separator  
GS  group separator  
RS  record separator  
US  unit separator  
SP  space  
DEL  delete, intended to be ignored 
Exercises:
c) Represent "The 4th of July." (without quotes) in 7bit ASCII, in binary.
d) What range of Unicode values is encoded in 4 consecutive bytes in the UTF8 encoding?
e) If the DEC PDP8 made a comeback, we might want a Unicode UTF12 encoding for that machine's 12 bit word. Following the coding scheme of UTF8, what range of Unicode values would you encode in one 12bit word? In two 12bit words? In three 12bit words?
Our assembly language, SMAL, contains two features that directly support
the ASCII character set. The first is its support for characters as operands
for assembly into memory as bytes, halfwords or words (although the most common
use is as bytes). The second feature is the ASCII directive for
storing the consecutive bytes of a string in memory. As a result, we could
store the text Hello in three different ways, as illustrated below:
B 2#01001000 B 2#01100101 B 2#01101100 B 2#01101100 B 2#01101111 B "H" B "e" B "l" B "l" B "o" ASCII "Hello" 
This example shows the same 5character string being encoded in three different ways, producing a total of 15 consecutive bytes of data. We could have encoded this with a single line reading ASCII "HelloHelloHello". There is no difference at all between the data loaded in memory by these three different methods. Once it is loaded in memory, all data becomes nothing but patterns of bits with no inherent meaning. Nothing in the result records how the data got into memory.
SMAL has no direct support for control characters other than SP, space, although as we will see, it is possible to define identifiers with any desired value. We can therefore define each of the control characteres by name, for example, giving NUL the meaning 0000 0000 and LF the meaning 0000 1010.
It is possible to associate arbitrary bit patterns with numeric values. For example, nothing, prevents us from deciding to represent zero as 1101 and one as 1000. Using such a mapping from binary values to the integers makes arithmetic extremely difficult  in effect, this arbitrary mapping forces us to use tablelookup schemes for all arithmetic operations.
Table lookup has been used as the basis of all arithmetic on at least one computer, the IBM 1620, codenamed the Cadet during development in the late 1950s. Later, someone decided that the name should be interpreted as the acronym "Can't Add, Doesn't Even Try," because the Cadet used tablelookup to compute the results of arithmetic operations. Some programmers even loaded new tables so they could do arithmetic in bases other than 10, the base for which the machine was designed.
With few exceptions, computers today use variations on the binary number system for integer arithmetic. This system has its roots in ancient China, where it was used to order the 64 combinations of the IChing sticks (each stick could be in one of two states; the pattern resulting from a throw of the sticks was used for fortune telling):
0  =  000000  16  =  010000  32  =  100000  48  =  110000  
1  =  000001  17  =  010001  33  =  100001  49  =  110001  
2  =  000010  18  =  010010  34  =  100010  50  =  110010  
3  =  000011  19  =  010011  35  =  100011  51  =  110011  
4  =  000100  20  =  010100  36  =  100100  52  =  110100  
5  =  000101  21  =  010101  37  =  100101  53  =  110101  
6  =  000110  22  =  010110  38  =  100110  54  =  110110  
7  =  000111  23  =  010111  39  =  100111  55  =  110111  
8  =  001000  24  =  011000  40  =  101000  56  =  111000  
9  =  001001  25  =  011001  41  =  101001  57  =  111001  
10  =  001010  26  =  011010  42  =  101010  58  =  111010  
11  =  001011  27  =  011011  43  =  101011  59  =  111011  
12  =  001100  28  =  011100  44  =  101100  50  =  111100  
13  =  001101  29  =  011101  45  =  101101  61  =  111101  
14  =  001110  30  =  011110  46  =  101110  62  =  111110  
15  =  001111  31  =  011111  47  =  101111  63  =  111111 
We must distinguish between the representation of a number and its abstract value. When we say ten, we are naming an abstract value, without reference to any number system. In English, we have simple names for all values up to twelve. When we write "12", we are using a decimal representation for the value we call twelve. This twelve is itself a representation, a string of italic lowercase letters encoding a sound. This sound is related to its abstract value only by the cultural conventions of the English speaking world.
In what follows, we will use a programming language notation, where unquoted numerals stand for abstract integer values, subject to arithmetic operations, while quoted strings stand for concrete representations of those values. Thus, the string "011100" is just a string of symbols, with no inherent meaning. It could be equivalent to eleven thousand one hundred if we decided to interpret it as a decimal number, or it could be the binary representation of the number twenty eight.
Consider, first, the formula that relates representations of decimal numbers to their values:
digits(S)1  
value(S) =  Σ  v(S[i]) × 10^{i} 
i = 0 
Users of the decimal system usually speak of the one's place, the ten's place, the hundred's place and so on. To illustrate the use of this formula, consider the following:
value("1024") = v("1") × 10^{3} + v("0") × 10^{2} + v("2") × 10^{1} + v("4") × 10^{0} 
In thinking about the above example, it is important to distinguish between "1", the numeral, which is a character, v("1"), the application of the numeric value function v to this numeral, and one, the actual value computed by the application of this function. As humans, we confuse these all the time, rarely distinguishing between the numeral, a symbol, and the abstract value it represents. Inside a computer, this distinction is crucial.
The formula given above can be directly reduced to code in a high level programming language. For example, the following C code will convert from decimal numbers, passed as a string, to the corresponding binary value, encoded in a variable of type int:
int value( char S[] ) { int i; int a = 0; for (i = 0; i < strlen(S); i++) { a = a + v[S[i]] * (int)pow( 10, i ); } return a; }
This function converts decimal to binary because it assumes that values of type int are represented in binary, and it assumes that the computer performing this computation is a binary computer. This code is awful for several reasons: It uses the floatingpoint pow function to compute 10^{i} on each iteration; it could have simply taken the multiplier from the previous iteration and multiplied it by 10. Second, it uses the table v to find the integer values each digit in the string; there are much faster ways of doing this. Third, it computes the length of the string using strlen(S) over and over with each iteration of the loop; it could have done this just once, up front. Finally, and from the point of view of human users, most importantly, the digits in the string are interpreted backwards, so the least significant digit is on the left, where our conventions demand that the least significant digit go on the right.
Exercises:
f) Convert the above function to the language of your choice and write a small program to try it out on some real strings of digits, giving as output the string it converted and the value of that string.
g) Fix the code you just wrote so it avoids reevaluating the stringlength with each iteration.
h) Fix the code you just wrote so it avoids using an exponential function, but instead starts with a multiplier of 1 and multiplies this by 10 on each iteration.
i) Fix the code you just wrote so it evaluates the digits of the number in their conventional order.
The formula given above applies equally well for computing the abstract value of a binary number, with the simple restriction that each binary digit, or bit may take on only two values, 0 and 1, and that the base of the number system is 2 instead of 10:
digits(S)1  
value(S) =  Σ  v(S[i]) × 2^{i} (binary) 
i = 0 
If we evaluate this formula using decimal arithmetic, as we would typically do with pencil and paper, it is an excellent formula for converting from binary to decimal. If we evaluate it using binary arithmetic on a binary computer, it is a useful way to convert from the textual representation of a binary number to the representation of that number in a single integer variable.
Just as we speak of the one's place, the ten's place and the hundred's place in decimal numbers, we speak of the one's place, the two's place, the four's place and the eight's place with binary numbers. The list of powers of 2 generally becomes very familiar to users of binary numbers:
i  2^{i}  i  2^{i} 

0  1  8  256 
1  2  9  512 
2  4  10  1,024 
3  8  11  2,048 
4  16  12  4,096 
5  32  13  8,192 
6  64  14  16,384 
7  128  15  32,768 
8  256  16  65,536 
i  2^{i}  

10  1,024  =~ 1,000 = 1K (kilo) 
20  1,048,576  =~ 1,000,000 = 1M (mega) 
30  1,073,741,824  =~ 1,000,000,000 = 1G (giga) 
40  1,099,511,627,776  =~ 1,000,000,000,000 = 1T (tera) 
Note that each power of two is twice the previous power of two, and note the convenient coincidence that 2^{10}, 1024, is within a few percent of 10^{3}, 1000. This allows quick estimates of the magnitude of binary numbers  if you have a binary number with 10 bits, it will be close to a 3digit decimal number, while if it has 20 bits, it will be close to a 6digit decimal number.
Exercises:
j) What is 2^{24}? Several machines were once built with 24bit words.
k) What is 2^{32}, in decimal, exactly. This is relevant on machines with a 32bit word!
l) The maximum number that can be represented in 6bits in binary is 63 while 2^{6} is 64. The maximum number that can be represented in 2digits in decimal is 99 while 10^{2} is 100. What is the maximum number than can be represented in nbits, as a function of n?
To convert to decimal with pencil and paper, write the place values over each bit position, in decimal, then sum the product of each place value times the digit under it. For binary, this is easy because we only multiply by 0 or 1. For example, to convert 10101011_{2} to decimal, we proceed as follows:
128  64  32  16  8  4  2  1 
1  0  1  0  1  0  1  1 
10101011_{2} = 128 + 32 + 8 + 2 + 1 = 171
To convert from decimal to binary using pencil and paper, repeatedly divide the number by two, writing the integer part of the quotient below the number and the remainder off to the side. Repeat until you get a quotient of 0, and the column of remainders you are left with will be the binary number, reading up from bottom to top. So, to convert 171 to binary, we proceed as follows:
171  
85  1  
42  1  
21  0  
10  1  
5  0  
2  1  
1  0  
0  1  10101011_{2} 
The above two exercises confirm each other: The final result is the same as the original value.
Exercises:
m) Flip a coin 8 times (or use any other random process) in order to make an 8bit binary number. Convert it to decimal. Convert the result back to binary to check your work!
n) Write a little program that takes two decimal integers as input n and b, and prints out n in base b. The program should work for values of b from 2 to 10. In C, C++ and Java, the / and % operators return the quotient and remainder, respectively, for positive operands.
How do we relate the characters used to represent digits to their abstract numeric values? When working with pencil and paper, we use rules we learned in elementary school. These may seem so natural that they pass unnoticed. With computers, we need to be very explicit. The most general solution to this uses an array indexed by characters, where each array entry gives the integer value of the corresponding character. Many programming languages allow the use of character values for array indexing, although some programmers get nervous when they see A['b'], which means the element of the array A selected by the character 'b'. The following conversion function based on a table works for the 7bit ASCII character set in C or C++ (add 128 more entries at the end, all 0, to make it work for 8bit ASCII):
int v(char d) { /* a function v of a character returning an integer */ static values[128] = { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,1,2,3, 4,5,6,7, 8,9,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }; return values[d]; }
This is computationally fast, but there is no need for array indexing here. The reason is, almost all character codes used on computers have assigned consecutive values to the symbols for the 10 decimal digits. This was true even with the odd character set of ILLIAC I. As a result, the following works:
int v(char d) { /* a function v of a character returning an integer */ return d  '0'; }The above code is legal C and C++, and similar code is legal in Java and C#. In languages descended from C, characters and numbers are members of the same abstract type, the integers. In some languages, strong type checking prevents integers and characters from being mixed, so explicit conversions are needed to get the integer representation of a character or the character represented by an integer. For example, consider this bit of Pascal code exactly equivalent to the C code given above:
function v(d: char): integer; begin v = int(d)  int('0'); end;In Pascal, the builtin function int() asks for the integer used to represent a character. It is not really a function, but just an instruction to the compiler to take the binary code that used to represent a character and treat it as an integer. A good Pascal compiler should produce the exact same machine code for this function as a C compiler.
Any positive integer radix r may serve as the base of a number system. The formula used above generalizes to:
digits(S)1  
value(S) =  Σ  v(S[i]) × r^{i} (radix r) 
i = 0 
Note that, for any radix r, the string "10" in that radix has the value r. Thus, in binary, 10 means two, in decimal, the string 10 means ten, and in octal, the string 10 means eight. To avoid confusion, the the number in printed work is sometimes given as a numerical subscript in base ten, as in:
10110_{2} = 26_{8} = 22_{10} = 211_{3}
As long as the radix r is ten or less, the conventional digits 0 to 9 can be used. For r greater than ten, additional digit symbols are needed. Historically, a variety of symbols have been used. For example, in base 12 also called duodecimal, the digits T for ten and E for eleven have been used. On ILLIAC I, base 16 was called sexadecimal, and they used the following digits:
0123456789KSNJFL
The most common convention for bases greater than ten is to use A for ten, B for eleven, C for twelve, and so on, up to Z. This allows bases as high as 36, although base 16, hexadecimal, is the highest common base. Thus, the hexidecimal digits are:
0123456789ABCDEF
It is common to use bases 8 and 16 when working with binary numbers. This is the result of grouping binary digits in groups of three or four. We routinely group digits of long numbers in decimal as well. Usually, we group them into threes, so we write 1,234,567 instead of 1234567. In effect, this grouping of decimal digits shifts us to base 1000 with three character names for each digit and commas between the digits. So 1,234,567 has 1 in the million's place, 234 in the thousand's place, and 567 in the one's place.
Consider the representation of one thousand in binary, a fairly long number:
1000 = 512 + 256 + 128 + 64 + 32 + 8
1000_{10} = 1111101000_{2}
We can group the digits of this number in order to improve readability. If we group the bits in groups of 3, we can treat each triplet of bits as an octal (base 8) digit, and if we group the digits in groups of 4, we can treat each group of bits as a hexadecimal digit:
1000_{10} = 1,111,101,000_{2} = 1750_{8}
1000_{10} = 11,1110,1000_{2} = 3E8_{16}
For integers, regardless of the number base, we always group digits from the least significant end of the number, leaving the odd leftovers for the most significant bits.
The pencil and paper conversion algorithms given for binary actually work for any placevalue number system. To convert to decimal from base r, write successive powers of r over successive digits, starting with 1 over the least significant digit, then multiply each digit by the power of r above it and sum the products. To convert a decimal number to base r, divide repeatedly by r, setting aside the remainders, until you get zero, and then write the remainders in order, last to first, as digits of the number.
Some programmers get so used to using the octal or hexadecimal number systems as abbreviations for binary numbers that they will refer to those bases as being binary numbers. This kind carelessness is fairly natural and common, but technically, it is wrong.
Exercises:
o) Given the numbers 1_{b}, 10_{b}, 100_{b} and 1000_{b}, where b is the unknown number base, what are the decimal equivalents for these numbers, assuming that the base is 2? Assuming that it is 8? Assuming that it is 10?
p) The letters A through F are sufficient to spell many words, and we can augment them with misreadings of the digits 0 and 1 as the capital letters O and I to spell even more words. So, what decimal value, when converted to hexadecimal, spells the words BEEF, FEED, FOOD, and CODE? What are the corresponding binary values? What are the corresponding octal values?
q) Flip a coin 8 times, in sequence, and write down 1 for each time it comes up heads, and 0 for each time it comes up tails in order to make an 8bit binary number. Convert that to decimal. Convert the result to octal, and then replace each digit by it's 3bit binary representation. You should get your original number back.
r) Flip a coin 8 times, in sequence, and write down 1 for each time it comes up heads, and 0 for each time it comes up tails in order to make an 8bit binary number. Convert that to decimal. Convert the result to hexadecimal, and then replace each digit by it's 4bit binary representation. You should get your original number back.
As we have already seen, the our assembly language, SMAL, supports binary representations of data to be assembled into memory, along with the use of the ASCII code for text. In fact, SMAL offers support for all of the common number bases and many uncommon number bases. For example, the letter A, which is represented as 1000001_{2}, can be represented in SMAL in the following different forms, among many others:
B "A" ; ASCII B 2#1000001 ; binary B 3#2102 ; base 3 B 4#1001 ; base 4 B 8#101 ; base 8, octal B 10#65 ; base 10, decimal B 65 ; also decimal B 16#41 ; base 16, hexadecimal B #41 ; also hexadecimal 
In the above, note that the ASCII, decimal and hexadecimal representations have special privileges. For all other systems of representation, the number base must be given explicitly (in decimal), followed by a number sign, followed by the number in that base. In the case of decimal numbers, the number is given directly, while a poundsign used without a number base as a prefix is used to represent hexadecimal.
For those who are curious, the SMAL assembler includes a general conversion
routine to handle multiple number bases.
The This operates in any number
base up to 36. The limit of base 36 is set by the fact that there are 26
letters in the alphabet plus 10 decimal digits available for use as digits
in higher radix numbers.
It is common, in the modern world, to hear that some nuclear weapon has an explosive yield equivalent to so many megatons of TNT, or that a disk has a capacity of so many gigabytes, or that a computer has so many megabytes of main memory. Units of measurement like the kilometer and the millimeter are also widely used. It is important to remember that the multipliers used for such units, multipliers like kilo and milli, have precise meanings that are defined by international standards as part of the SI system of measurement, otherwise known as the metric system:
1T  =  1  tera  =  1,000,000,000,000  
1G  =  1  giga  =  1,000,000,000  
1M  =  1  mega  =  1,000,000  
1K  =  1  kilo  =  1,000  
1  =  1  =  1  
1m  =  1  milli  =  .001  
1µ  =  1  micro  =  .000,001  
1n  =  1  nano  =  .000,000,001  
1p  =  1  pico  =  .000,000,000,001 
In the world of computers, we have online disk subsystems with capacities measured in terabytes, or Tbytes, and we have CPU clock speeds measured in gigahertz or GHz. Small microcontrollers have memory capacities measured in kilobytes or Kbytes, and data communications lines may have lengths measured in kilometers or Km. We also have memory speeds measured in nanoseconds or ns, chip sizes measured in square millimeters or mm, and we have disk access times measured in milliseconds, ms. Note that capitalization is used to indicate whether the multiplier is greater than or less than one, and note the use of the Greek letter mu, µ standing for micro. For example, microseconds are frequently written as µseconds. It is handy to remember that the speed of light is remarkably close to one foot per nanosecond.
When someone tells you that their memory has a capacity of 100Kb, unfortunately, you are in trouble. Chip designers will tend to use this to refer to kilobits or Kbits, while computer system designers will expect it to stand for kilobytes or Kbytes. As a rule, spell it out if there is any doubt!
In the world of computer science, it is common to use one K or one kilo to refer to a multiplier is 1024, but in fact, this usage is only approximate. In the world of disks, it is common to use strange mixed approximations, where mega means 1000×1024. To distinguish multipliers that are powers of 2 from multipliers that are powers of 10, it has been suggested that we should use the subscript 2 to indicate the common computer science approximation, while reserving the unsubscripted form for the exact SI prefix.
1 kilo_{2} = 1024
1 mega_{2} = 1,048,576
Of course, this leaves us with no convenient notation for the disk salesman's definition of a megabyte as 1000 times 1024. Fortunately, this absurd usage is in decline.
The International Electrotechnical Commission recommends that we use the prefix kibibyte to refer to 1024 bytes, mebibyte for 1024^{2} bytes and gibibyte for 1024^{3} bytes, with the abbreviations KiB, MiB and GiB, respectively. These terms are an official standard, but there are other standards. As Andrew Tannenbaum once said, "the great thing about standards is that there are so many to chose from."
Exercises:
s) How long is a microfortnight, in seconds.
t) How heavy is a kilodram (weight), in pounds? How heavy is a megadram in tons? (Be careful to use the definition of a dram as a unit of weight, because it is also defined as a unit of volume.)
On computers, we generally are forced to work in terms of a fixed word size, so our numbers are composed of a fixed number of bits. Leading zeros are used to pad a number out to the desired width. Thus, on a machine with a 16bit word,
100_{10} = 0000,0000,0110,0100_{2} = 0064_{16}
On a 16bit machine, the maximum representable number is
65535_{10} = 1111,1111,1111,1111_{2} = FFFF_{16}
When deciding between octal and hexadecimal for compact representation of numbers, it is common to select one that divides words and bytes evenly, so for machines based on an 8 bit byte, hexadecimal seems a good choice, while for machines with a 6 bit byte, octal makes sense.
There are exceptions to this. The Motorola 68000 and the DEC PDP11, were essentially 16bit machines with 8bit bytes, but on these machines, the instruction encoding used four 3bit fields. The Intel 8080 was an 8bit machine with two 3bit fields per instruction. It was convenient on these machines to print the contents of memory in octal in order to expose these 3bit fields as octal digits. The Unix system and the C programming language were first implemented on the PDP11 system, so to this day, Unix and C tend to default to octal.
To add two decimal numbers, for example, to add 132 to 39, we arrange the numbers as follows:
1  3  2  augend  
+  3  9  addend  

And then do the addition one pair of digits at a time, starting with 2+9. To add one pair of digits, we use an addition table that most of us should have memorized in elementary school. This same table would have been loaded in the memory of the IBM 1620 Cadet, which did arithmetic using a tablelookup instead of an adder built from digital logic:
+  0  1  2  3  4  5  6  7  8  9  

0  0  1  2  3  4  5  6  7  8  9  
1  1  2  3  4  5  6  7  8  9  10  
2  2  3  4  5  6  7  8  9  10  11  
3  3  4  5  6  7  8  9  10  11  12  
4  4  5  6  7  8  9  10  11  12  13  
5  5  6  7  8  9  10  11  12  13  14  
6  6  7  8  9  10  11  12  13  14  15  
7  7  8  9  10  11  12  13  14  15  16  
8  8  9  10  11  12  13  14  15  16  17  
9  9  10  11  12  13  14  15  16  17  18  
10  11  12  13  14  15  16  17  18  19 
For the example, looking up 2+9 in the table gives a sum of 11; we split this sum into two pieces, the sum digit and the carry digit, writing the result as follows:
1  carry  
1  3  2  augend  
+  3  9  addend  
 
1  sum 
The next column creates a problem: Our addition table only allows adding two numbers, but there are three in that column. One solution is to use the same addition table, but to step down a row when we have to add in a carry. This is why an extra row was given in the above table. Using this trick, we get:
1  carry  
1  3  2  augend  
+  3  9  addend  
 
7  1  sum 
Finally, we add up the column in the hundred's place. For this example, this is trivial:
1  carry  
1  3  2  augend  
+  3  9  addend  
 
1  7  1  sum 
Recall that the value of a simple binary number, represented as a string S of digit symbols, is defined as:
digits(S)1  
value(S) =  Σ  v(S[i]) × 2^{i} 
i = 0 
This is the same placevalue scheme we use for decimal numbers, except that the 1's, 10's and 100's places are now the 1's, 2's and 4's places. As a result, binary arithmetic strongly resembles decimal arithmetic. Binary addition can be done using exactly the approach described above, but with a much smaller addition table.
+  0  1  

0  0  1  
1  1  10  
10  11 
This may seem too simple, but that is because the rules are the same as for decimal arithmetic or any other placevalue number system. The only change is in the number of values each digit can take on. This means that remembering things like the addition and multiplication tables is far easier in binary than in decimal. We pay a penalty, of course, because there are more binary digits in a particular number than there are decimal digits. It takes 4 binary digits to represent a quantity that would be comfortably represented in 1 decimal digit, and it takes ten bits to represent a 3 digit decimal number. Converting decimal to binary, adding the binary numbers using the above rules, and converting the binary sum back to decimal gives:
decimal  binary  

1  carry  1  
1  3  2  augend  1  0  0  0  0  1  0  0  
+  3  9  addend  +  1  0  0  1  1  1  
  
1  7  1  sum  1  0  1  0  1  0  1  1 
If there is a limit on the number of bits allowed, as on a computer with a fixed word size, we say that an overflow has occurred if the carry out of the topmost bit of our fixed size word is nonzero. Note that this applies to words used to hold unsigned data, and that the conventions for detecting overflow are more complex if we are also interested in representing negative numbers.
Exercises:
u) Flip a coin 16 times to produce 2 8bit binary numbers. Add them in binary, and then convert the original numbers to decimal, add them, and convert the result back to binary in order to check your sum.
Subtraction in binary is as easy as subtraction in decimal. The rules are the same as in decimal, but with more digits and simpler tables for each digit. There is one major difference: Subtraction leads to negative numbers, and these are not usually represented in computers the way we represent them on paper!
Consider the problem of representing positive and negative numbers using 4 bits for each number. If we follow our habits from the world of pencil and paper, we can reserve one bit to represent the sign while the other bits hold the binary representation of the magnitude. This is called the signed magnitude number system In this system, we can think of the sign bit as representing either + or –, while the 3 magnitude bits have the usual binary numeric interpretation. This gives us the following 16 values:
0  0  0  0  +0  1  0  0  0  –0  
0  0  0  1  +1  1  0  0  1  –1  
0  0  1  0  +2  1  0  1  0  –2  
0  0  1  1  +3  1  0  1  1  –3  
0  1  0  0  +4  1  1  0  0  –4  
0  1  0  1  +5  1  1  0  1  –5  
0  1  1  0  +6  1  1  1  0  –6  
0  1  1  1  +7  1  1  1  1  –7 
The signed–magnitude system works, but unfortunately, it is harder to build hardware to add numbers in this system than in alternative systems. As a result, it is not commonly used for integer arithmetic today. This was not obvious to computer developers in the 1940s and 1950s; many early computers used the signed magnitude system. Today, the signed magnitude system is still used for floating point numbers.
Signed magnitude numbers pose one annoyance because positive zero and negative zero have different representations. This means that two numbers can have different representations but equal values.
To negate a signed magnitude number, you flip the sign bit from one to zero or from zero to one. Adding is harder: You must either add or subtract the magnitudes, depending on whether the signs are the same or not, and then set the sign of the result according to a rather complex set of rules.
An alternative way to make negative numbers is to arrange things so that the negative of a number is obtained by reversing all the bits of the corresponding positive number. This leads to the one's complement number system, illustrated with the following table of 4bit signed numbers:
0  0  0  0  +0  1  0  0  0  –7  
0  0  0  1  +1  1  0  0  1  –6  
0  0  1  0  +2  1  0  1  0  –5  
0  0  1  1  +3  1  0  1  1  –4  
0  1  0  0  +4  1  1  0  0  –3  
0  1  0  1  +5  1  1  0  1  –2  
0  1  1  0  +6  1  1  1  0  –1  
0  1  1  1  +7  1  1  1  1  –0 
The operation of negating a one's complement number is called taking the one's complement of a number or one's complementing the number. So, the one's complement of 0000 is 1111 and the one's complement of 1111 is 0000. Note that negating a negative number produces a positive number, and visa versa. Also note that the one's complement operator is well defined even when other number systems are being used. The operator is defined in terms of its effect on the binary representation, not in terms of the interpretation of that representation.
Warning: Many students get confused by the use of the term one's complement to mean both the name of the number system and the name of the operator used to negate numbers in that system! If someone says: "Take the one's complement of x," or "one's complement x" that means to apply the operator, reversing each bit in x; the number of bits in the result will be the same as the number of bits in x. If someone says: "write x as a 4bit one's complement number," that means to use the number system!
As was noted above, adding two signed magnitude numbers is fairly difficult. In contrast, the rules for adding two one's complement numbers are simple, but far from obvious: Treat the most significant bit exactly like all the other bits, and compute the unsigned binary sum of the two numbers. Then, if this addition produces a carry out of the topmost bit, add one to the result. This is called an end around carry.
This rule for addition is so simple that, when building computer hardware to do one's complement arithmetic, subtraction is always done by adding the one's complement of the subtrahend to the minuend. One's complement has been used as the primary representation for integers on many computers, almost all designed prior to 1965.
Note that one's complement numbers and signed magnitude numbers share the problem with there being two representations of zero, +0 and –0. This is eliminated when two's complement numbers are used. In the two's complement system, numbers are negated by taking the one's complement and then adding one. This idea is far from obvious, but the result is the dominant number system used on today's computers.
0  0  0  0  0  1  0  0  0  –8  
0  0  0  1  +1  1  0  0  1  –7  
0  0  1  0  +2  1  0  1  0  –6  
0  0  1  1  +3  1  0  1  1  –5  
0  1  0  0  +4  1  1  0  0  –4  
0  1  0  1  +5  1  1  0  1  –3  
0  1  1  0  +6  1  1  1  0  –2  
0  1  1  1  +7  1  1  1  1  –1 
The two's complement operator is defined as take the one's complement and then add one. It is important to note that applying this operator twice to an nbit number always produces the original value. So, for example, the two's complement of 0101 is 1011 and the two's complement of 1011 is 0101.
The two's complement number system has an annoying feature: It cannot representa the negation of the most negative number. In 4 bits, for example, the value –8 is represented as 1000, but there is no 4bit two's complement representation of +8. If you apply the two's complement operator to 1000 you get 1000 back.
Despite this, two's complement arithmetic is the dominant system used on all modern computers. Among the advantages of this system are that there are no problems with multiple representations of zero. Applying the two's complement operator to 0000 gives 0000 after we discard the carry out of the high bit. Another advantage is that odd numbers always have a one in their least significant bit, whether they are positive or negative. Similarly, all two's complement numbers that are evenly divisible by 4 end in 00, and all that are evenly divisible by 8 end in 000, no matter what the sign.
The fundamental reason for the popularity of two's complement numbers is that arithmetic is trivial. To add two two's complement numbers, just treat all bits as magnitude bits, even the most significant bit that you might think of as a sign bit.
To subtract one two's complement number from another, one's complment the
number to be subtracted (the subtrahend), then add it to the other number
(the minuend) plus one. Using C notation (which is
also C++ and Java notation),  is the two's complement operator and
~ is the one's complement operator, the following lines of
code are all equivalent:
A  B 
A + B 
A + (~B + 1) 
(A + ~B) + 1 
Note that with two's complement subtraction, a carry of one into any bit
position means, in essence, don't borrow from this position. This may seem
an odd way of handling borrows, but it works.
Warning: As was the case with one's complement arithmetic, many students get confused by the use of the term two's complement to mean both the name of the number system and the name of the operator used to negate numbers in that system! If someone says: "Take the two's complement of x," or "two's complement x" that means to apply the operator; the number of bits in the result will be the same as the number of bits in x. If someone says: "write x as a 4bit two's complement number," that means to use the number system, not negate the number.
The two's complement number system turns out to be a strange place value
system, in which the "sign bit" has a value that is negative. Thus, in
addition to the obvious ways of converting two's complement numbers to
decimal (if negative, write down a minus sign, then two's complement it
to create a positive number, then convert that to decimal), we can do the
conversion using the sum of the place values. For the 8 bit two's
complement system, the place values are:
–128  64  32  16  8  4  2  1 
1  0  1  0  1  0  1  1 
10101011_{2} = –128 + 32 + 8 + 2 + 1 = –85
When adding two two's complement numbers, overflow detection is not as simple
as looking for a carry out of the top bit. If the numbers being
added were of opposite sign, the sum must lie between them, so overflow is
impossible. If the numbers were of the same sign, overflow is
possible, and when it occurs, the sign of the result will differ from the sign
of the two numbers. Alternately, this turns out to be equivalent
to asking if the carry into the sign position is the same as the carry out of
the sign position — in adding negative numbers,
there should always be a carry both into and out of the sign,
and in adding positive numbers, there should
never be a carry in or carry out of the sign.
As an aside, 2's complement numbers have a strong relationship to what is called the ten's complement number system in decimal, sometimes known as the odometer number system. To compute the 10's complement of a number, first take the 9's complement by subtracting every digit from 9, then add 1 to the result. So, –1, as a 6digit 10's complement number, is represented by 999999, and –2 is 999998.
There are other number systems. For example, there are biased numbers, in which a fixed bias is added to the abstract value to guarantee a positive value before the value is represented in binary. The most natural bias for nbit numbers is 2^{n–1}. Here is an example, in 4 bits:
0  0  0  0  –8  1  0  0  0  0  
0  0  0  1  –7  1  0  0  1  +1  
0  0  1  0  –6  1  0  1  0  +2  
0  0  1  1  –5  1  0  1  1  +3  
0  1  0  0  –4  1  1  0  0  +4  
0  1  0  1  –3  1  1  0  1  +5  
0  1  1  0  –2  1  1  1  0  +6  
0  1  1  1  –1  1  1  1  1  +7 
Biased number systems seem odd, but they are commonly used in representing the exponent field for floating point numbers. Biased numbers have the advantage that sorting the representations into simple binary order puts the abstract values in numerical order. This is not true for any of the other systems we discussed. As with two's complement numbers, biased numbers always have at least one value that cannot be negated.
Curiously, when the bias used with nbit numbers is 2^{n–1}, the biased representation of a value v is the same as the two's complement representation of v with the most significant bit inverted. So, for example, –8 as a 4bit two's complement number is 1000 and as a 4bit number biased by 8, it is 0000.
Exercises:
v) Flip a coin 8 times to produce an 8bit binary number. What abstract value does this number represent in the signed magnitude system. Check your result by converting back to binary in the signedmagnitude system.
w) Flip a coin 8 times to produce an 8bit binary number. What abstract value does this number represent in the one's complement system. Check your result by converting back to binary in the one's complement system.
x) Flip a coin 8 times to produce an 8bit binary number. What abstract value does this number represent in the two's complement system. Check your result by converting back to binary in the two's complement system.
y) Flip a coin 8 times to produce an 8bit binary number. What abstract value does this number represent in the biased number system with the default bias for 8bit numbers. system. Check your result by converting back to binary in the biased number system.