Illustration of "Number, bases. How to convert decimal, hexadecimal and binary ?"

Bases

A base is a set of symbols (digits) that can be used to represent a value (number).

  • Decimal base = 0 1 2 3 4 5 6 7 8 9
  • Hexadecimal base = 0 1 2 3 4 5 6 7 8 9 A B C D E F (a = 10, b = 11, ...)

The significance of each digit depends on its position (power of N, where N is the number of digits in the base).

Bases

A base is a set of symbols (digits) that can be used to represent a value (number).

  • Decimal base = 0 1 2 3 4 5 6 7 8 9
  • Hexadecimal base = 0 1 2 3 4 5 6 7 8 9 A B C D E F (a = 10, b = 11, ...)

The significance of each digit depends on its position (power of N, where N is the number of digits in the base).

General rule: for a base containing N symbols, the value V of a number written S (Si = the symbol at the position i, i is between 0 and N-1): V = SUM(Si * N^i)

Example 1

In decimal (N = 10), the number written 51 = 1 * 10^0 + 5 * 10^1 = 1 + 50

Example 2

In hexadecimal (N = 16), the number written a12 = 2 * 16^0 + 1 * 16^1 + a * 16^2 = 2 + 16 + a * 256 = 2 + 16 + 10 * 256 = 2 + 16 + 2560 = 2578

In a computer

Representation for programmers

In order to avoid programmers to be mistaken with bases, they are prefixed:

  • hexadecimal: 0x.... or h... or \x... (example: 0xF0)
  • binary: 0b.... (example: 0b1100
  • octal: 0..... (example: 016)
  • decimal: no prefix, default

Bit sizes

In computer science, an amount of bits is stored for each number. It is important because storing bits take place in the computer memory. The max value of a number using n-bits is 2^n-1.

Negative numbers

Several notation exists but only one is used: two-s complement. Negative numbers begin at 0b11111111 (-1) and decrement from it to 0b11111110 (-2), ...

Rule: for a negative value A, A xor 0b1111111 = -A-1.

Example: 0b11111110 = -2, 0b00000001 = 1

 Endianess

In computer, words (4 bytes (8 bits) ) might be represented in 2 ways:

  • big endian: 0x12345678 is represented 0x12 0x34 0x56 0x78
  • little endian: 0x12345678 is represented 0x78 0x56 0x34 0x12

Example

int a = 0x12345678;
char *b = &a;
b[0] = 0x00;
// depending on the architecture, a is now = 0x00345678 or 0x12345600

Floats

In computer, real number have an approximation (floats, double). It is written m * r ^ e.

  • m: mantissa
  • r: radix
  • e: exponent

Unicode, characters set

In computer, a character might be represented with 1 byte (8 bits). It is ASCII. Lots of characters exist. They are encoded with different tables using fixed or dynamic length (8, 16 bits, even more).

Example

In unicode, \au00E4 is ä