The value represented by a decimal number

From high school:

 Value of the decimal number  12  is computed as: 

     1×101  +  2×100  
   = 1×10   +  2×1        (in decimal arithmetic)  
   

Remember that:

  • We write expressions in decimal numbers in our programs

  • The compiler will translate the numbers into 2s compl repr !!!

  • Therefore:

      • All calculations in a computer program are performed in binary 2s compl code !!!

What we write in a program and what operations the computer will perform
 

We write arithmetic operations in base 10 arithmetic in programs:

   x = 1×10  +  2×1; //  = 12 
   
 

The compiler will translate and instruct the computer to perform the arithmetic operations in 2s complement arithmetic:

          1    ×  10        +     2    ×   1;
          |        |              |        |      (compiler !)
          V        V              V        V
   x = 00000001×00001010    +  00000010×00000001  
     = 00001010 + 00000010
     = 00001100               (= 12(10))

 Note:

    I used 8 bits in example. 
    In reality, the computer will use 32 bits
    (because int typed data is 32 bits).
   

How to convert (= map) a number string of 2 digits
 

Example:

  • Convert the string "12" into its 2s complement code

    (Result = 00000....0001100))

 

Step 1:   map each digit to its 2s complement code

 "12"  consists of the ASCII code:  00110001 00110010

 Map each ASCII code uisng  "char - 48":

    00110001 (=49) - 00110000 (=48) -->  00000001 (=1)
    00110010 (=50) - 00110000 (=48) -->  00000010 (=2)
   

How to convert (= map) a number string of 2 digits
 

Example:

  • Convert the string "12" into its 2s complement code

    (Result = 00000....0001100))

 

Step 2:   compute the value (with binary arithmetic

    00000001×00001010    +  00000010×00000001  
  = 00001010 + 00000010
  = 00001100

 (I did the arithmetic in 8 bits, 
  the computer program will use 32 bits)
   

How to convert (= map) a number string of 2 digits

Implementing the conversion algorithm in Java:

 String  s = input string; // Need to use string of 2 digits
 int[]   v = new int[2];   // Variable used to save values of the digits
 int     x;

 // Convert each ASCII character to 2's compl

 v[0] = s.charAt(0) - '0';
 v[1] = s.charAt(1) - 48;  // It's the same !

 // Find the 2s compl code using (binary) arithmetic

 x = v[0]*10 + v[1]; 
                  // Note: calculation will be
                  //  performed in BINARY by computer ! 
   

Remember:   we write expressions in decimal, compiler will translate into binary
DEMO:   /home/cs255001/demo/atoi/ConvStr2Digits.java

Quiz to test your understanding
 

Quiz:

  • What happens when you enter:

            s = "::"

              ???