/8分で読めます

数の基数とは?Binary、Decimal、Hexなどを解説

目にするnumberはすべて、何らかのbaseで書かれています。この考え方を理解すると、binary、octal、decimal、hexadecimal、colors、memory addresses、file permissionsがずっと読みやすくなります。

Number Baseとは?

number baseradixとも呼ばれ、number systemが使うunique digitsの数です。baseは使えるsymbolsと、各positionの価値を決めます。

Base 10、つまりdecimalは10個のdigits、0から9を使います。digitsを使い切ると次のpositionへcarryします。number 10は文字通り「tenのgroupが1つ、onesが0個」を意味します。

同じ考え方はどのbaseでも使えます。Binaryは0と1の2 digits、Octalは0から7の8 digits、Hexadecimalは0から9とAからFの16 digitsを使います。

Positional Notation: 基本の考え方

すべてのnumber basesの中心にある考え方はpositional notationです。digitのvalueは置かれたpositionによって決まり、各positionはbaseのpowerになります。

In base B, the number d3 d2 d1 d0 equals:

  d3 x B^3 + d2 x B^2 + d1 x B^1 + d0 x B^0

Example in decimal (B=10):
  4725 = 4x10^3 + 7x10^2 + 2x10^1 + 5x10^0
       = 4000   + 700    + 20     + 5
       = 4725

Same idea in binary (B=2):
  1101 = 1x2^3 + 1x2^2 + 0x2^1 + 1x2^0
       = 8     + 4     + 0     + 1
       = 13 decimal

このpatternが腑に落ちると、どのbase conversionも、base valueが違うだけの同じ考え方になります。

Computingで重要な4つのBases

BaseNameDigitsPrefix用途
2Binary0, 10bhardware states、bits、logic gates、CPU instructions
8Octal0-70oUnix permissionsと古いsystems
10Decimal0-9(none)日常のcountingとuser-facing values
16Hexadecimal0-9, A-F0xcolors、memory addresses、bytes、MAC addresses

同じvalueを複数のbasesで書くと次のようになります。

DecimalBinaryOctalHexadecimal
0000
510155
10101012A
42101010522A
100110010014464
25511111111377FF
1000111110100017503E8

255はbinaryでは11111111、hexではFFです。これは1 byteに収まる最大値なので、byte valuesにはhexがよく使われます。

Bases間の変換方法

Any Base to Decimal

各digitに、そのpositionに対応するbaseのpowerを掛け、結果を足し合わせます。

Binary 10110 -> Decimal:
  1x2^4 + 0x2^3 + 1x2^2 + 1x2^1 + 0x2^0
  = 16  + 0     + 4     + 2     + 0
  = 22

Hex 2F -> Decimal:
  2x16^1 + Fx16^0
  = 32   + 15
  = 47

Octal 37 -> Decimal:
  3x8^1 + 7x8^0
  = 24  + 7
  = 31

Decimal to Any Base

target baseで繰り返し割り、remaindersを集めます。remaindersを下から上へ読むと変換結果になります。

Convert 47 to binary:
  47 / 2 = 23 remainder 1
  23 / 2 = 11 remainder 1
  11 / 2 =  5 remainder 1
   5 / 2 =  2 remainder 1
   2 / 2 =  1 remainder 0
   1 / 2 =  0 remainder 1

Read upward: 101111
47 decimal = 101111 binary

Convert 47 to hex:
  47 / 16 = 2 remainder 15 (F)
   2 / 16 = 0 remainder 2

Read upward: 2F
47 decimal = 2F hex

Power-of-2 Shortcuts

2のpowerであるbases間では、decimalを経由せずbinary digitsを直接group化できます。

  • Binary to octal: 2^3 = 8なので、binary digitsを3つずつgroupにします。
  • Binary to hex: 2^4 = 16なので、binary digitsを4つずつgroupにします。
  • Octal to hex: octalをbinaryへ展開し、bitsを4-bit chunksへ再group化します。
Binary to Hex (group by 4 from right):
  1010 1111 0011
  = A    F    3
  = 0xAF3

Binary to Octal (group by 3 from right):
  101 011 110 011
  = 5   3   6   3
  = 0o5363

なぜComputersはDecimalではなくBinaryを使うのか?

decimalが人間にとって自然なら、なぜcomputersはbinaryを使うのでしょうか。短い答えはphysicsです。

  • Transistorsは自然にbinary - on/off、conducting/not conductingの状態を取ります。
  • Binaryはnoiseに強い - 10個のvoltage rangesより、2つのrangesを確実に区別するほうが簡単です。
  • Boolean logicはbinaryにきれいに対応する - true/false operationsは1/0 circuitsになります。
  • Simple circuitsはscaleしやすい - 小さく信頼できるbinary circuitsをchipsに何十億個も詰め込めます。

Hexとoctalは、computersが内部でdataを処理する形式そのものではありません。binary patternsを人間にとってcompactで読みやすく書く方法です。

見かけることがあるUnusual Bases

主要な4つ以外にも、特定のcontextsで登場するbasesがあります。

BaseName見かける場所
3Ternaryexperimental ternary computersとbalanced ternary algorithms
12Duodecimaltime、dozens、1 foot = 12 inchesのようなmeasurements
36Base-360-9とA-Zを使うcompact IDsやURL shorteners
58Base-58紛らわしいcharactersを避けるBitcoin-style addresses
64Base-64email、data URIs、JWTs、binary-to-text formats向けのdata encoding

CodeでのBase Conversion

多くのprogramming languagesには、よく使うbase conversionsのbuilt-in functionsがあります。

JavaScript

// Decimal to other bases
(255).toString(2);    // "11111111" binary
(255).toString(8);    // "377" octal
(255).toString(16);   // "ff" hex
(255).toString(36);   // "73" base-36

// Other bases to decimal
parseInt("11111111", 2);  // 255
parseInt("377", 8);       // 255
parseInt("ff", 16);       // 255
parseInt("73", 36);       // 255

// Literals in code
const bin = 0b11111111;   // 255
const oct = 0o377;        // 255
const hex = 0xFF;         // 255

Python

# Decimal to other bases
bin(255)    # '0b11111111'
oct(255)    # '0o377'
hex(255)    # '0xff'

# Other bases to decimal
int("11111111", 2)   # 255
int("377", 8)        # 255
int("ff", 16)        # 255

# Any base to any base via decimal
def convert_base(number_str, from_base, to_base):
    decimal = int(number_str, from_base)
    if to_base == 10:
        return str(decimal)
    digits = []
    alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
    while decimal > 0:
        digits.append(alphabet[decimal % to_base])
        decimal //= to_base
    return ''.join(reversed(digits)) or '0'

C

#include <stdio.h>

int x = 255;

printf("Decimal: %d\n", x);  // 255
printf("Octal:   %o\n", x);  // 377
printf("Hex:     %x\n", x);  // ff
printf("Hex:     %X\n", x);  // FF

int bin = 0b11111111;  // 255 in C23 / GCC extension
int oct = 0377;        // 255
int hex = 0xFF;        // 255

Real-World Applications

development workでさまざまなbasesが登場する例です。

CSS Colors (Hex)

#FF5733はred=255、green=87、blue=51を意味します。hex digitsの各pairが1 color byteです。

File Permissions (Octal)

chmod 755はownerにread/write/execute、groupとothersにread/executeを設定します。各digitは3 permission bitsをencodeします。

Memory Addresses (Hex)

debuggersやsystem toolsは0x7FFE1234ABCDのようなaddressesを表示します。hexはcompactでbyte boundariesに揃うためです。

IP Addresses and Subnets (Binary)

subnet masksはbinaryで見ると理解しやすくなります。network prefixは1 bitsの連続で、その後にhost 0 bitsが続くからです。

Short URLs (Base-36/Base-62)

URL shortenersは大きなnumeric IDsをdQw4w9Wのようなcompact stringsへencodeします。

任意のNumber Base間で変換

無料のBase Converter toolで、binary、octal、decimal、hexadecimal、そして2から36までの任意のbaseへbrowser内ですぐに変換できます。

Base Converterを試す

参考資料

  1. Knuth, D.E. (1997). The Art of Computer Programming, Volume 2: Seminumerical Algorithms. Chapter 4.1: Positional Number Systems. Addison-Wesley Professional.
  2. Petzold, C. (2000). Code: The Hidden Language of Computer Hardware and Software. Microsoft Press.
  3. Mozilla Developer Network. Number.prototype.toString(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
  4. Python Software Foundation. Built-in Functions: int(). https://docs.python.org/3/library/functions.html#int
  5. IEEE Computer Society. IEEE 754-2019: Standard for Floating-Point Arithmetic. https://standards.ieee.org/ieee/754/6210/