Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

General number bases (binary, octal, decimal, hex...) #232

Open Qingquan-Li opened 1 year ago

Qingquan-Li commented 1 year ago

Numbers can use nearly any base, such as base 5 or base 17. Popular bases are:

1. From any base to decimal

Converting from any base to decimal is straightforward: Each digit's decimal value is multiplied by each digit's decimal weight, and summed.

Examples:

Base 2 (binary) to decimal:

1111111 = 1 27 + 1 26 + 1 25 + 1 24 + 1 23 + 122 + 1 21 + 1 20 = 255

Base 8 (octal) to decimal:

107 = 182 + 0 81 + 7 * 80 = 64 + 0 + 7 = 71

Base 16 (hexadecimal) to decimal:

2b = 2 161 + 11 160 = 32 + 11 = 43

2. From decimal to any base

Converting from decimal to any base can be done using a simple algorithm. The decimal is divided by the base, and remainder put in the rightmost digit. The process repeats with the quotient and the next digit, until the quotient is 0.

Examples:

Decimal to Base 2 (binary):

1310:

13 ÷ 2 = 6...1 6 ÷ 2 = 3...0 3 ÷ 2 = 1...1 1 ÷ 2 = 0...1

= 11012

Decimal to Base 5:

7310:

73 ÷ 5 = 14...3 14 ÷ 5 = 2...4 2 ÷ 5 = 0...2

= 3425

3. Any base to any base

To convert a number in any base B directly to any other base C, a straightforward approach first converts the base B number to a decimal number, then converts that decimal number to base C.

Example:

To convert 3205 to base 8, one starts with 3205 = 3×52 + 2×51 +2×50 = 8510 followed by converting to base 8: 85 ÷ 8 = 10 remainder 5, 10 ÷ 8 = 1 remainder 2, 1 ÷ 8 = 0 remainder 1, so concatenating yields 1258