In [ ]:
%autosave 0

Binary Integer (2's complement)

In most CPU, 2's complement is used in order to represent Signed Integer.

4bit integer Unsigned Value Signed Value
0b0000 0 0
0b0001 1 1
0b0010 2 2
0b0011 3 3
0b0100 4 4
0b0101 5 5
0b0110 6 6
0b0111 7 7
0b1000 8 -8
0b1001 9 -7
0b1010 10 -6
0b1011 11 -5
0b1100 12 -4
0b1101 13 -3
0b1110 14 -2
0b1111 15 -1
Value 4bit Unsign 4bit Signed 8bit Unsign 8bit Signed 16bit Signed 32bit Signed 64bit Signed
0 0b0000 0b0000 0b00000000 0b00000000 0x0000 0x00000000 0x0000000000000000
----- ----------- ----------- ----------- ----------- ------------ ------------ ------------
Min 0b0000 0b1000 0b00000000 0b10000000 0x8000 0x80000000 0x8000000000000000
Min val 0 -8 0 -128 -32768 $-2^{31}$ $-2^{63}$
----- ----------- ----------- ----------- ----------- ------------ ------------ ------------
Max 0b1111 0b0111 0b11111111 0b01111111 0x7fff 0x7fffffff 0x7fffffffffffffff
Max val 15 7 255 127 32767 $2^{31} -1$ $2^{63} -1$
----- ----------- ----------- ----------- ----------- ------------ ------------ ------------
-1 N/A 0b1111 N/A 0b11111111 0xffff 0xffffffff 0xffffffffffffffff

$2^{31}=2147483648 \fallingdotseq 2 \cdot 10^{9} \\ 2^{63}=9223372036854775808 \fallingdotseq 9 \cdot 10^{18}$


In [ ]:
# print 2**7, 2**15, 2**31, 2**63
import math

for exp in (7, 15, 31, 63):
    val = 2 ** exp
    log10 = round(math.log(val, 10), 2)
    print ('2**', exp, '=', val, '-> 10**', log10)

Sign conversion

Converting from positive integer to negative, or nagative integer to positive can be done by following steps.

  1. Reverse all bits of original integer (1's complement, for example 0b0101 -> 0b1010)
  2. add 1 (ignore overflow)

Sample of C source

#include <stdio.h>

int main(void) {
    int orig_int[10] = {0, 1, 100, 99, 17, -1, -100, -23, -1000, -123} ;
    int i ;

    for (i=0; i<10; i++) {
        int rev ;
        rev = (~orig_int[i]) + 1 ;
        printf("from: %d (%08x), to: %d (%08x)\n",
             orig_int[i], orig_int[i], rev, rev) ;
    }

    return 0 ;
}

Save above C source code as integer.c

Compile

$ gcc -o interger integer.c

or

$ make integer

Execute

$ ./integer

Endian(Byte Order), Big endian and Little endian

In case of big endian, MSB(Most significant byte) is located at lowest address. In case of little endian, LSB(Least Significant Byte) is located at lowest address. This is determined by CPU's architecture. Intel CPU is Little endian, IBM Mainframe is Big endian. Following tables shows how 32bit integer(value=0x0a0b0c0d)is stored in memory address 0x1000.

Endian 0x1000 0x1001 0x1002 0x1003
Big 0x0a 0x0b 0x0c 0x0d
Little 0x0d 0x0c 0x0b 0x0a