Programming Search⌘K

Conceptcore

Binary number

Also called binary number, binary, base 2, binary numeral system, binary literal, bit string, hexadecimal, octal, radix, number base, positional notation.

A binary number writes a value in base 2, with the digits 0 and 1. Computers store integers this way, and hexadecimal and octal are short forms of the same bits.

Applies to
core-languages

Idea

In decimal, each digit is worth ten times the digit to its right. In binary, each digit is worth two times the digit to its right, and the only digits are 0 and 1. So 101101 means 1×32 + 0×16 + 1×8 + 1×4 + 0×2 + 1×1, which is 45. A binary digit is a bit, and a switch, a charge or a magnetic spot can hold one, so computers store and add numbers in binary. People rarely write long binary numbers; they write the same bits in hexadecimal, base 16, where each digit stands for exactly 4 bits.

def to_binary(n):
    """Repeated division by 2: each remainder is the next bit, from the lowest."""
    bits = ""
    while n > 0:
        n, r = divmod(n, 2)
        bits = str(r) + bits
    return bits or "0"


def from_binary(bits):
    """Each step doubles the value so far and adds the next bit."""
    n = 0
    for b in bits:
        n = 2 * n + int(b)
    return n


n = 45
b = to_binary(n)
print(n, "->", b)
print(" + ".join(f"{d}*2^{i}" for i, d in reversed(list(enumerate(reversed(b)))) if d == "1"), "=", from_binary(b))
print("built-ins:", bin(n), int("101101", 2), f"{n:08b}")

# Binary addition: add bit by bit from the right, with a carry.
x, y = "1011", "0110"
carry, out = 0, ""
for a, c in zip(reversed(x), reversed(y)):
    s = int(a) + int(c) + carry
    out = str(s % 2) + out
    carry = s // 2
out = ("1" if carry else "") + out
print(f"{x} + {y} = {out}  ({from_binary(x)} + {from_binary(y)} = {from_binary(out)})")
Output
45 -> 101101
1*2^5 + 1*2^3 + 1*2^2 + 1*2^0 = 45
built-ins: 0b101101 45 00101101
1011 + 0110 = 10001  (11 + 6 = 17)

to_binary divides by 2 again and again, and the remainders are the bits from the lowest to the highest. from_binary goes the other way: for each bit, it doubles the value so far and adds the bit. The sum on the second line shows the place value of each 1 bit. The built-ins do the same work: bin adds the prefix 0b, int with base 2 parses, and the format 08b pads to 8 digits. The addition works like decimal addition by hand, with a carry of 1 when a column adds up to 2 or 3.

How it works

Place values. A number in base b with digits dₙ … d₁ d₀ has the value dₙ·bⁿ + … + d₁·b + d₀. In base 2 the place values are 1, 2, 4, 8, 16 and so on, so n bits can hold the values from 0 to 2ⁿ − 1: 8 bits hold 0 to 255, 32 bits hold 0 to 4,294,967,295. The number of bits that a value needs is its bit length, ⌊log₂ n⌋ + 1 for n > 0, so 45 needs 6 bits and 2¹⁰⁰ needs 101.

Conversion. To write n in base 2, divide by 2 and keep the remainder until the quotient is 0, then read the remainders backward. To read a binary number, start with 0 and, for each bit from the left, double and add the bit. The same two loops work for any base, which is why library functions take the base as an argument. JavaScript's toString takes a radix, "An integer in the range 2 through 36", and uses the letters a to z for digits above 9.2

Hexadecimal and octal. 16 is 2⁴, so each hexadecimal digit is exactly 4 bits, and two digits are one byte: 0xAC is 1010 1100. 8 is 2³, so each octal digit is 3 bits. This makes the conversion between them and binary a matter of grouping the bits, with no arithmetic, and it is why programmers write masks, colours, addresses and byte values in hexadecimal. Octal survives in Unix file permissions, where 755 is the three groups of bits 111 101 101.

Literals and conversion in languages. Most languages accept integer literals in several bases with a prefix: 0b or 0B for binary, 0o or 0 for octal and 0x for hexadecimal. The Go specification says: "An optional prefix sets a non-decimal base: 0b or 0B for binary, 0, 0o, or 0O for octal, and 0x or 0X for hexadecimal".6 Most also allow a separator, _ or ' in C++, to group digits. Functions convert in both directions: Python's bin converts "an integer number to a binary string prefixed with "0b"",1 C# has the format specifier B, which "converts a number to a string of binary digits",4 Go's strconv.ParseInt takes a base,5 and C's strtol takes a base from 2 to 36 and stops at the first character that is not a digit of that base.8

Negative numbers. A binary number with a minus sign, such as -101, is how mathematics writes negative values, and Python prints bin(-5) that way because its integers have no fixed width. Machines store negative integers in a fixed number of bits, almost always in two's complement, where −5 in 8 bits is 11111011. Functions that print the bits of a fixed-width integer show this form: Java's Integer.toBinaryString gives "a string representation of the integer argument as an unsigned integer in base 2",3 and in Rust, "negative values are formatted as the two's complement representation".7

Fractions. Binary also has a point: 0.1 in binary is one half, and 0.011 is three eighths. A fraction whose denominator is not a power of 2, such as one tenth, has no finite binary form, just as one third has no finite decimal form. This is why 0.1 + 0.2 is not exactly 0.3 in floating-point arithmetic.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the binary literals, toString(2) and parseInt of JavaScript, and the type number is a 64-bit float, but no example file exists.
GoNative
RustNative
KotlinNativeKotlin has 0b literals with underscores, Int.toString(2) and String.toInt(2), and the JVM methods of Integer, but no example file exists because kotlinc is not installed.
SQLNativeThe current SQL standard and PostgreSQL accept 0b, 0o and 0x integer literals, and some databases have bit-string types, but other databases do not support them yet.
BashNativeBash arithmetic reads numbers in any base from 2 to 64 with the form base#digits, such as $((2#101101)), but printf has no binary conversion, and no example file exists.
PowerShellNativePowerShell has 0b literals and the .NET method [Convert]::ToString(value, 2), but no example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no numbers.
CSSDoes not applyCSS writes colours in hexadecimal, such as.
Regular expressionsDoes not applyA pattern such as [01]+ matches binary digits as text but has no numbers.
Language Verdict Mechanism
Python native 0b literals; bin, int(s, 2), format b; int.bit_length, int.bit_count
JavaScript native 0b literals; toString(2), parseInt(s, 2); BigInt
TypeScript native as JavaScript
Java native 0b literals; Integer.toBinaryString, Integer.parseInt(s, 2)
Kotlin native 0b literals; toString(2), toInt(2)
C# native 0b literals; format B; Convert.ToString(x, 2)
Go native 0b literals; %b; strconv.FormatInt, strconv.ParseInt
Rust native 0b literals; {:b}; from_str_radix
C native 0b literals in recent standards; strtol with base 2
C++ native 0b literals; std::bitset; std::format with b; std::from_chars
Bash native 2#101101 in arithmetic; $((16#ff))
PowerShell native 0b literals; [Convert]::ToString(x, 2)
SQL native 0b, 0o and 0x integer literals in the current standard and PostgreSQL; bit-string types
Regex n/a [01]+ matches binary digits as text
HTML n/a no numbers
CSS n/a hexadecimal colours such as #ff8000, no binary

All the general-purpose languages in the table write binary literals and convert numbers to and from binary text, so the verdict is native. They differ in how they show negative numbers: Python and JavaScript print a minus sign, while Java, C#, Go's unsigned formats, Rust and C++ show the two's complement bits at the width of the type. Bash reads numbers in any base from 2 to 64 with the form base#digits.

The example files show literals, printing, parsing and bit counts in each language. Python shows a negative number with a sign, and masks it to get its 8 bits. JavaScript shows the limit of exact integers in a 64-bit float and the 32-bit bitwise operators. Java and C# print negative numbers as 32 bits of two's complement. Go reports an error for a digit that is not binary. Rust formats negative values at their own width. C writes its own printing function and shows where strtol stops. C++ uses std::bitset, which "represents a fixed-size sequence of N bits",9 and the functions of <bit>.

PythonGitHub
n = 0b1010_1100  # binary literal; the underscore only groups digits
print(n, oct(n), hex(n), bin(n))
print(int("ff", 16), int("0b1010", 0), int("777", 8))
print(f"{5:b} {5:08b} {255:#x} {1_000_000:_b}")

# Python integers have no fixed width, so a negative number shows a minus sign.
print(bin(-5), (-5).bit_length(), (2**100).bit_length())
# Masking with 0xFF gives the low 8 bits, as an 8-bit register would hold them.
print(f"{-5 & 0xFF:08b}", (0b1011).bit_count())
Output
172 0o254 0xac 0b10101100
255 10 511
101 00000101 0xff 1111_0100_0010_0100_0000
-0b101 3 101
11111011 3
  • Verdict: native. Python writes literals in base 2, 8 and 16, and int parses any base from 2 to 36; base 0 reads the prefix from the text. The format _b groups binary digits by four. Python integers have no fixed width, so bin(-5) has a minus sign, and & 0xFF gives the 8 bits that a byte would hold. bit_length and bit_count give the number of bits needed and the number of 1 bits.
#include <bit>
#include <bitset>
#include <charconv>
#include <cstdint>
#include <format>
#include <iostream>
#include <string_view>

int main() {
    std::uint32_t n = 0b1010'1100; // binary literal; the quote groups digits
    std::cout << std::format("{} {:b} {:o} {:x} {:08b} {:#b}\n", n, n, n, n, 5, 5);
    std::cout << std::bitset<8>(n) << ' ' << std::bitset<8>(static_cast<std::uint8_t>(-5)) << '\n';

    std::string_view s = "101101";
    int v = 0;
    auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), v, 2);
    std::cout << v << ' ' << (ec == std::errc{}) << '\n';

    std::cout << std::popcount(n) << ' ' << std::countl_zero(n) << ' ' << std::bit_width(200u) << ' '
              << std::has_single_bit(64u) << '\n';
}
Output
172 10101100 254 ac 00000101 0b101
10101100 11111011
45 1
4 24 8 1
  • Verdict: native. std::format has the type b for binary, and # adds the prefix. std::bitset<8> prints a value as exactly 8 bits. std::from_chars parses binary text without exceptions or locales and reports errors in ec. The header <bit> has popcount, countl_zero, bit_width and has_single_bit, which compile to single instructions where the processor has them.
JavaGitHub
public class Main {
    public static void main(String[] args) {
        int n = 0b1010_1100; // binary literal; the underscore groups digits
        System.out.println(n + " " + Integer.toBinaryString(n) + " " + Integer.toOctalString(n) + " " + Integer.toHexString(n));
        System.out.println(Integer.parseInt("101101", 2) + " " + Integer.parseInt("-ff", 16) + " " + Long.parseLong("777", 8));

        // toBinaryString shows all 32 bits of a negative int, in two's complement.
        System.out.println(Integer.toBinaryString(-5));
        System.out.println(Integer.parseUnsignedInt("11111111111111111111111111111011", 2));
        System.out.println(Integer.bitCount(n) + " " + Integer.numberOfLeadingZeros(n) + " " + Integer.highestOneBit(n));
        System.out.println(String.format("%8s", Integer.toBinaryString(5)).replace(' ', '0'));
    }
}
Output
172 10101100 254 ac
45 -255 511
11111111111111111111111111111011
-5
4 24 128
00000101
  • Verdict: native. Integer.toBinaryString treats the int as unsigned, so −5 prints as 32 bits of two's complement, and parseUnsignedInt reads those bits back as −5. parseInt takes a radix and a sign. bitCount, numberOfLeadingZeros and highestOneBit work on the bits directly. Java has no format for binary, so padding needs String.format and replace.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

/* printf has no binary conversion in older C libraries, so write the digits by hand. */
static void print_bits(unsigned value, int width) {
    for (int i = width - 1; i >= 0; i--) putchar(value >> i & 1u ? '1' : '0');
    putchar('\n');
}

int main(void) {
    unsigned n = 0xAC; /* hexadecimal: each digit is 4 bits */
    printf("%u %o %x %X\n", n, n, n, n);
    print_bits(n, 8);
    print_bits((unsigned)-5, 32); /* conversion to unsigned gives the two's complement bits */

    char *end;
    long v = strtol("101101", &end, 2);
    printf("%ld, rest \"%s\"\n", v, end);
    v = strtol("1012", &end, 2); /* stops at the first digit that is not binary */
    printf("%ld, rest \"%s\"\n", v, end);

    printf("bits in unsigned: %zu\n", sizeof(unsigned) * CHAR_BIT);
    return 0;
}
Output
172 254 ac AC
10101100
11111111111111111111111111111011
45, rest ""
5, rest "2"
bits in unsigned: 32
  • Verdict: native. C has octal and hexadecimal conversions in printf, and the program prints binary with its own loop, because a %b conversion is new and not in every C library. Converting −5 to unsigned gives its two's complement bits. strtol with base 2 stops at the first digit that is not binary and sets end to the rest, so the caller must check that nothing is left.
using System.Globalization;
using System.Numerics;

int n = 0b1010_1100; // binary literal with a digit separator
Console.WriteLine($"{n} {n:B} {n:X} {Convert.ToString(n, 8)}");
Console.WriteLine($"{5:B8} {Convert.ToString(-5, 2)}");

// Parse binary and hexadecimal text.
Console.WriteLine(int.Parse("101101", NumberStyles.AllowBinarySpecifier));
Console.WriteLine(Convert.ToInt32("ff", 16));

Console.WriteLine($"{BitOperations.PopCount((uint)n)} {BitOperations.LeadingZeroCount((uint)n)} {BitOperations.Log2(200u)}");
// BigInteger has no fixed width.
Console.WriteLine((BigInteger.One << 70).GetBitLength());
Output
172 10101100 AC 254
00000101 11111111111111111111111111111011
45
255
4 24 7
71
  • Verdict: native. The format specifier B prints binary digits, and B8 pads to 8 digits. Convert.ToString takes a base of 2, 8, 10 or 16 and shows a negative int as 32 bits. NumberStyles.AllowBinarySpecifier parses binary text. BitOperations counts bits and finds the highest set bit, and BigInteger.GetBitLength works at any size.
JavaScriptGitHub
const n = 0b1010_1100; // binary literal with a numeric separator
console.log(n, n.toString(2), n.toString(8), n.toString(16));
console.log(parseInt("101101", 2), Number("0b1010"), parseInt("z", 36));
console.log((5).toString(2).padStart(8, "0"));

// Numbers are 64-bit floats: integers are exact only up to 2^53.
console.log(2 ** 53 === 2 ** 53 + 1, Number.MAX_SAFE_INTEGER.toString(2).length);
// Bitwise operators work on 32-bit two's complement integers.
console.log((-5 >>> 0).toString(2), (-5).toString(2));
// BigInt has no fixed width.
console.log((2n ** 70n).toString(2).length, BigInt.asUintN(8, -5n).toString(2));
Output
172 10101100 254 ac
45 10 35
00000101
true 53
11111111111111111111111111111011 -101
71 11111011
  • Verdict: native. toString and parseInt take a radix from 2 to 36, and Number reads the 0b prefix. A JavaScript number is a 64-bit float, so integers are exact only up to 2⁵³, and Number.MAX_SAFE_INTEGER has 53 one bits. The bitwise operators work on 32-bit two's complement, so -5 >>> 0 shows its 32 bits, while toString(2) prints a minus sign. BigInt.asUintN gives the low bits at any width.
package main

import (
	"fmt"
	"math/big"
	"math/bits"
	"strconv"
)

func main() {
	n := 0b1010_1100 // binary literal with a digit separator
	fmt.Printf("%d %b %o %x %08b\n", n, n, n, n, 5)
	fmt.Println(strconv.FormatInt(-5, 2), strconv.FormatUint(uint64(uint8(251)), 2))

	v, err := strconv.ParseInt("101101", 2, 64)
	fmt.Println(v, err)
	_, err = strconv.ParseInt("102", 2, 64)
	fmt.Println(err)
	w, _ := strconv.ParseUint("ff", 16, 8)
	fmt.Println(w)

	fmt.Println(bits.OnesCount(uint(n)), bits.LeadingZeros8(uint8(n)), bits.Len(200))
	x := new(big.Int).Lsh(big.NewInt(1), 70)
	fmt.Println(x.BitLen(), x.Text(16))
}
Output
172 10101100 254 ac 00000101
-101 11111011
45 <nil>
strconv.ParseInt: parsing "102": invalid syntax
255
4 0 8
71 400000000000000000
  • Verdict: native. The verb %b prints binary, and strconv.FormatInt prints a negative number with a minus sign; converting to an unsigned type first shows its bits. strconv.ParseInt takes a base and a bit size and returns an error for a digit that is not valid, so the program does not silently accept 102. math/bits counts bits, and math/big handles integers of any size.
RustGitHub
fn main() {
    let n: u32 = 0b1010_1100; // binary literal; the underscore groups digits
    println!("{n} {n:b} {n:o} {n:x} {:08b} {:#010b}", 5, 5);

    // A negative number prints its two's complement bits at the width of its type.
    println!("{:b} {:b}", -5i8, -5i32);

    println!("{:?} {:?}", u8::from_str_radix("101101", 2), u8::from_str_radix("100000000", 2).is_err());
    println!("{:?}", i64::from_str_radix("-ff", 16));

    println!("{} {} {} {}", n.count_ones(), n.leading_zeros(), n.trailing_zeros(), 200u32.ilog2());
    println!("{}", u128::MAX.count_ones());
}
Output
172 10101100 254 ac 00000101 0b00000101
11111011 11111111111111111111111111111011
Ok(45) true
Ok(-255)
4 24 2 7
128
  • Verdict: native. The format {:b} prints binary, {:08b} pads it and {:#010b} adds the 0b prefix inside the width. A negative value prints its two's complement bits at the width of its own type, 8 bits for i8 and 32 for i32. from_str_radix returns an error when the value does not fit, as nine bits do not fit in a u8. The methods count_ones, leading_zeros, trailing_zeros and ilog2 work on any integer type.
  • Bits of fixed width. Machine integers have 8, 16, 32 or 64 bits, and arithmetic wraps around or overflows at the top. See integer overflow and bits and bytes.
  • Binary-coded decimal. BCD stores each decimal digit in 4 bits, which keeps decimal fractions exact; old business machines, some calculators and the x86 instruction set support it.
  • Gray code. A binary order in which two neighbouring values differ in one bit, used in rotary encoders and Karnaugh maps.
  • Balanced ternary and other bases. The Soviet Setun computer of 1958 used base 3 with the digits −1, 0 and 1. Base 64 and base 32 encode bytes as text. See Base64.
  • Bit sets. An integer or an array of bits can hold a set of small numbers, with one bit per member, and bitwise operators give union and intersection.

Pitfalls

  • Leading zeros in literals. In C, C++, Java and JavaScript in sloppy mode, a literal such as 0755 is octal, so 010 is 8. Python 3 and strict-mode JavaScript reject it. Use 0o where the language has it.
  • Signed and unsigned output. The same 32 bits print as -5 or 4294967291 depending on the type, and binary output functions differ: Python prints -0b101, Java prints 32 bits. Say which form a protocol or file uses.
  • Parsing that stops early. strtol, parseInt and similar functions stop at the first character that is not a digit and return what they read, so parseInt("102", 2) is 2. Check that the whole string was used, or use a function that reports an error, such as Go's strconv.ParseInt or Rust's from_str_radix.
  • Overflow in parsing. A long binary string does not fit in a 32-bit integer. Use a wider type, an unsigned parse or a big integer type.
  • Decimal fractions. Money and other decimal amounts are not exact in binary floating point. Store them in integer units, such as cents, or in a decimal type.

Cost

Converting a number of n bits to or from binary text takes O(n) steps for machine integers, and printing is cheap next to the cost of output. For big integers, the simple conversion to decimal takes O(n²) time, because each division by 10 touches all the digits; libraries use divide-and-conquer methods for very large numbers, and conversion to binary or hexadecimal stays linear because those bases are powers of 2. Counting bits, finding the highest bit and finding the lowest bit are single instructions on most processors, which the functions bit_count, popcount, count_ones and leading_zeros use.

History

Gottfried Wilhelm Leibniz published Explication de l'Arithmétique Binaire in 1703, with tables for addition and multiplication in base 2. George Boole's algebra of logic, from 1854, used the two values true and false. In 1937, Claude Shannon showed in his master's thesis that relay circuits compute Boolean algebra, and George Stibitz built a binary adder from relays on his kitchen table. Konrad Zuse's Z1 of 1938 and his later machines used binary.

The ENIAC of 1945 worked in decimal, but John von Neumann's EDVAC report of the same year argued for binary, and most later computers followed it. Programmers wrote octal on machines with words of 12, 18 or 36 bits, such as the PDP-8 and the IBM 7090. IBM's System/360 of 1964 used 8-bit bytes and documented its machine in hexadecimal, which became the usual form for bytes and addresses.

References

  1. Built-in Functions, Python documentation, bin() and int()
  2. Number.prototype.toString(), MDN Web Docs, Parameters
  3. Class Integer, Java SE 25 API documentation, toBinaryString(int)
  4. Standard numeric format strings, .NET documentation, Binary format specifier (B)
  5. Package strconv, Go standard library documentation, ParseInt and FormatInt
  6. The Go Programming Language Specification, Integer literals
  7. Trait Binary, Rust standard library documentation, Description
  8. strtol, strtoll, C reference, cppreference.com, Description
  9. std::bitset, C++ reference, cppreference.com, Description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/27NFBE/text.yaml