Disclosure: this post was written with AI assistance and checked by the FlashKit team. Every number below was produced by running the code shown.
Most developers can call bin() or toString(2) without thinking. Fewer can say what those functions are doing, or why -45 turns into 11010011 in one place and -101101 in another. This post covers the conversions by hand first, then the same steps in JavaScript and Python, then the sharp edges: fixed widths, negative numbers and a few common mistakes.
Decimal to binary: divide by 2
Each binary digit (bit) is a remainder. Divide the number by 2, write down the remainder, and repeat with the quotient until the quotient is 0. The remainders, read from last to first, are the binary number.
Here is 156:
| Step | Number | Divide by 2 | Remainder |
|---|---|---|---|
| 1 | 156 | 78 | 0 |
| 2 | 78 | 39 | 0 |
| 3 | 39 | 19 | 1 |
| 4 | 19 | 9 | 1 |
| 5 | 9 | 4 | 1 |
| 6 | 4 | 2 | 0 |
| 7 | 2 | 1 | 0 |
| 8 | 1 | 0 | 1 |
Read the remainders from the bottom up: 10011100. The first remainder is the least significant bit, which is why the order flips. If you would like to try other numbers and see the remainder table, the decimal to binary converter shows the same steps.
Binary to decimal: add up the bit weights
Going the other way, every position has a weight that is a power of 2, doubling as you move left. Take 10110101:
| Bit | 1 | 0 | 1 | 1 | 0 | 1 | 0 | 1 |
|---|---|---|---|---|---|---|---|---|
| Weight | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
Add the weights where the bit is 1: 128 + 32 + 16 + 4 + 1 = 181.
Fractions, briefly
For the part after the decimal point, multiply by 2 instead of dividing. The whole-number part of each result is the next bit; keep the fractional part and repeat. For 0.625:
- 0.625 x 2 = 1.25, bit 1
- 0.25 x 2 = 0.5, bit 0
- 0.5 x 2 = 1.0, bit 1, and the fraction is now 0, so stop
So 0.625 is 0.101 in binary, and 10.625 is 1010.101. Many fractions never reach 0. For example 0.1 starts 0.000110011001... and repeats forever, which is why it cannot be stored exactly in a float. I covered that in How floating-point numbers are stored, so the rest of this post sticks to integers.
Fixed widths and zero-padding
Computers store integers in fixed widths, usually 8, 16, 32 or 64 bits. A fixed width means you pad the left with zeros. 5 is 101 as a bare number, but in 8 bits it is 00000101, in 16 bits 0000000000000101, and in 32 bits 00000000000000000000000000000101.
The width also limits what fits. An unsigned n-bit value goes from 0 to 2^n - 1:
| Width | Unsigned range | Signed range (two's complement) |
|---|---|---|
| 8-bit | 0 to 255 | -128 to 127 |
| 16-bit | 0 to 65535 | -32768 to 32767 |
| 32-bit | 0 to 4294967295 | -2147483648 to 2147483647 |
The number 300 needs 9 bits (100101100), so it does not fit in 8 bits at all.
Negative numbers: two's complement
Binary has no minus sign in memory, so signed integers use two's complement. To write a negative number at a given width:
- Write the positive value, padded to the width.
- Flip every bit.
- Add 1.
For -45 in 8 bits:
45 = 00101101 flip bits = 11010010 add 1 = 11010011 So -45 is 11010011. As an unsigned byte that same pattern is 211, which is 256 - 45. That is the whole idea: at width n, the negative number -x is stored as 2^n - x.
To read a pattern back, check the top bit. If it is 0, read it normally. If it is 1, the top bit counts as a negative weight (-128 in 8 bits):
11010011 = -128 + 64 + 16 + 2 + 1 = -45
Or, equivalently, take the unsigned value (211) and subtract 256.
The same -45 at other widths is just sign extension: 1111111111010011 in 16 bits and 11111111111111111111111111010011 in 32 bits. If you want to check a value at 4, 8, 16, 32 or 64 bits without doing it on paper, the two's complement calculator converts both ways.
Hex as shorthand
Four bits make one hex digit, so hex is just binary grouped in fours. Split 10011100 into 1001 1100. That is 9 and C (12), so 156 is 0x9C. Going back, 0xB5 is 1011 0101, which is 10110101, or 181. This is why hex is the usual way to write bytes and bit masks.
The code: JavaScript
The built-ins first:
(156).toString(2); // "10011100" parseInt("10110101", 2); // 181 (5).toString(2).padStart(8, "0"); // "00000101" (156).toString(16); // "9c" And the division method, written out. It mirrors the table above:
function toBin(n) { if (n === 0) return "0"; let bits = ""; while (n > 0) { bits = (n % 2) + bits; // prepend the remainder n = Math.floor(n / 2); } return bits; } function fromBin(s) { let v = 0; for (const c of s) v = v * 2 + (c === "1" ? 1 : 0); return v; } console.log(toBin(156)); // 10011100 console.log(fromBin("10110101")); // 181 Negative numbers are where JavaScript surprises people. (-45).toString(2) gives "-101101", a minus sign plus the magnitude, not two's complement. Mask to a width to get the real bit pattern:
function toTwos(n, width) { return (n & ((1 << width) - 1)).toString(2).padStart(width, "0"); } function fromTwos(s) { const v = parseInt(s, 2); return s[0] === "1" ? v - 2 ** s.length : v; } console.log((-45).toString(2)); // -101101 console.log(toTwos(-45, 8)); // 11010011 console.log(toTwos(-45, 16)); // 1111111111010011 console.log(fromTwos("11010011")); // -45 console.log(fromTwos("10000000")); // -128 This works up to width 31. JavaScript's bitwise operators work on 32-bit signed integers, so for 32-bit patterns use (n >>> 0).toString(2), and for 64-bit use BigInt: BigInt.asUintN(64, -45n).toString(2).
The code: Python
bin(156) # '0b10011100' format(156, "b") # '10011100' int("10110101", 2) # 181 format(5, "08b") # '00000101' format(156, "x") # '9c' Python integers have no fixed width, so there is no "natural" two's complement. bin(-45) gives '-0b101101'. Masking with & (2**width - 1) produces the fixed-width pattern, because Python treats negative integers as having infinitely many leading 1 bits:
def to_twos(n, width): return format(n & (2**width - 1), f"0{width}b") def from_twos(s): v = int(s, 2) return v - (1 << len(s)) if s[0] == "1" else v print(bin(-45)) # -0b101101 print(to_twos(-45, 8)) # 11010011 print(to_twos(-45, 32)) # 11111111111111111111111111010011 print(from_twos("11010011")) # -45 print(from_twos("10000000")) # -128 Common mistakes
- Reading the remainders top-down. The first remainder is the lowest bit. Reverse them.
- Forgetting the width.
11010011is 211 unsigned and -45 signed. A bit pattern means nothing until you know the width and whether it is signed. - Overflowing the width. 200 fits in 8 bits unsigned (
11001000), but read as signed 8-bit that same pattern is -56.fromTwos(toTwos(200, 8))returns -56 for exactly this reason. - Trusting
parseInton bad input.parseInt("102", 2)returns 2, because it stops at the first invalid digit and does not warn you.parseInt("0b101", 2)returns 0. UseNumber("0b101")(5) if the prefix is present, and validate the string with a regex such as/^[01]+$/first. Python'sint("102", 2)raisesValueError, which is the safer behaviour. - Using
toString(2)for negatives and expecting two's complement. It prints a sign and magnitude. Mask first. - Mixing up flip-and-add-1 with just flipping. Flipping alone gives one's complement: 45 flipped is
11010010, which is -46 in two's complement, not -45.
Check your work
Do a few by hand, then compare against a tool. The binary converter shows decimal, binary, hex and octal side by side and lets you choose signed or unsigned and the bit width. It is a quick way to confirm that your manual loop and your masks agree. For the reverse direction with a positional sum, see the binary to decimal converter.
If you have a conversion that behaves oddly in your own language, leave it in the comments and I will take a look.