Binary Numbers: How Computers Count, Convert and Calculate
Computing Numeral systems Fundamentals Python JavaScript
Quick answer
A binary number is a number written in base 2, with only the digits 0 and 1, where each place is worth twice the place to its right: 1011_2=8+2+1=11. Computers use it because a switch has two states, and every number, letter and image is stored as a string of these bits. To convert, add the powers of 2 under the 1s, or divide by 2 repeatedly and read the remainders from the bottom up.
Key takeaways
- Binary is place value in base 2: the places are worth 1,2,4,8,16,…, and a digit is a bit, 0 or 1.
- n bits hold 2^n values, from 0 to 2^n-1; a byte is 8 bits and holds 256 values.
- Hexadecimal is shorthand for binary: one hex digit is exactly four bits, so
FFis 11111111_2=255. - In binary 1+1=10: add column by column, carrying 1; multiplying is shifting and adding, and doubling is adding a 0 at the end.
- Negative integers use two's complement: invert the bits and add 1, so -5 is 11111011 in 8 bits and the top bit is worth -2^n-1.
- A fraction terminates in binary only if its denominator is a power of 2, so 0.1 repeats (0.0(0011 repeating)_2) and a float can only store it approximately.
What is a binary number?
A binary number is written in base 2: it uses only the two digits 0 and 1, called bits (from binary digit), and each place is worth twice the place to its right. Ordinary decimal numbers work the same way with ten digits and places worth 1, 10, 100, 1000. In both, the value of a digit depends on where it stands, which is the idea of place value found in every positional system.
The place values in binary are the powers of 2, counted from the right starting at 2^0 (see exponents):
| Place | 2^7 | 2^6 | 2^5 | 2^4 | 2^3 | 2^2 | 2^1 | 2^0 |
|---|---|---|---|---|---|---|---|---|
| Value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
| Bit | 0 | 1 | 0 | 1 | 1 | 0 | 1 | 0 |
The number in the table is 01011010_2=64+16+8+2=90. A subscript 2 says the base, because 10_2 is two but 10 is ten.
Counting in binary is counting in decimal with only two digits. When the last digit reaches 1 the next count carries into the next place, as 9 becomes 10 in decimal:
| Decimal | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Binary | 0 | 1 | 10 | 11 | 100 | 101 | 110 | 111 |
| Decimal | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|---|
| Binary | 1000 | 1001 | 1010 | 1011 | 1100 | 1101 | 1110 | 1111 |
Why computers use binary. A transistor is either conducting or not, a magnetic spot points one way or the other, a pit on a disc is there or not. Two states are easy to tell apart even when the signal is noisy, so a machine can copy and process them without error; ten voltage levels would be far harder. Everything else, numbers, text, pictures and sound, is first turned into numbers and then into bits. The last bit also tells you something simple: a binary number is even when it ends in 0, as in the even and odd numbers of the integers article.
Try it: read a binary number
What is 1101_2 in decimal?
How do you convert between binary, decimal and hexadecimal?
To turn binary into decimal, add the place values of the 1s; to turn decimal into binary, divide by 2 again and again and read the remainders from the bottom up. Both use only the powers of 2.
Binary to decimal. 1011010_2 has 1s in the places worth 64, 16, 8 and 2, so it is 64+16+8+2=90.
Decimal to binary. Divide by 2, write down the remainder, and carry on with the quotient until it reaches 0. For 90:
| Division | Quotient | Remainder |
|---|---|---|
| 90÷2 | 45 | 0 |
| 45÷2 | 22 | 1 |
| 22÷2 | 11 | 0 |
| 11÷2 | 5 | 1 |
| 5÷2 | 2 | 1 |
| 2÷2 | 1 | 0 |
| 1÷2 | 0 | 1 |
Read the remainders upward: 1011010_2. This is the same division with remainder as in the integers article, and the last remainder is the leftmost digit because it is the highest place.
Octal and hexadecimal. Binary strings are long, so programmers group the bits. Three bits make one octal digit (base 8, digits 0 to 7) and four bits make one hexadecimal digit (base 16, digits 0 to 9 and then A to F for 10 to 15):
| Binary | 0000 | 0001 | 0010 | 0011 | 0100 | 0101 | 0110 | 0111 |
|---|---|---|---|---|---|---|---|---|
| Hex | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| Binary | 1000 | 1001 | 1010 | 1011 | 1100 | 1101 | 1110 | 1111 |
|---|---|---|---|---|---|---|---|---|
| Hex | 8 | 9 | A | B | C | D | E | F |
Group from the right: 01011010_2 is 0101 1010, which is 5A_16, and 5·16+10=90. A byte is always exactly two hex digits, which is why FF is 11111111_2=255. Hexadecimal is how colors are written on the web: #FF8800 is red 255, green 88_16=136 and blue 0, an orange. Octal survives in Unix file permissions, where 755 is 111 101 101, read, write and execute for the owner and read and execute for everyone else.
Type a number below in any base and see it in all four.
Interactive: convert between binary, octal, decimal and hexadecimal
Type a whole number in any of the four bases and see it in all of them, with the division ladder that produces its binary digits.
Try it: decimal to binary
Write 45 in binary.
Try it: hexadecimal
What is 2F_16 in decimal?
- 47
- 215
- 41
- 32
How do you add, subtract and multiply in binary?
Binary arithmetic uses the same column methods as decimal, with only four sums to remember: 0+0=0, 0+1=1, 1+0=1 and 1+1=10, which means write 0 and carry 1. Adding three 1s in a column gives 11_2: write 1 and carry 1.
Addition. Work from the right and carry to the left. For 1011_2+110_2:
Column by column, from the right: 1+0=1; 1+1=10, write 0 and carry 1; 0+1+1=10, write 0 and carry 1; 1+0+1=10, write 0 and carry 1; the carry becomes the leading 1. The result is 10001_2, and as a check 11+6=17.
Subtraction. When a column cannot take its digit away, borrow 1 from the column on the left, which is worth 2 in the column you are working on. For 1011_2-110_2 the answer is 101_2, and 11-6=5. Computers rarely subtract this way: they add the two's complement, in the section on negative numbers.
Multiplication. Each bit of the lower number gives either 0 or a copy of the upper number shifted left, and the copies are added. 101_2×11_2 is 101+1010=1111_2, and 5·3=15. There is no multiplication table to learn, only shifting and adding, which is why hardware multipliers are simple.
Doubling and halving. Appending a 0 doubles a binary number (101_2=5, 1010_2=10), as appending a 0 multiplies a decimal number by ten. Dropping the last bit halves it and discards the remainder. This is the idea behind the bit shifts below.
Try your own sums; the working is shown as a column layout.
Interactive: add, subtract and multiply in binary
Enter two binary numbers and watch the column working, with its carries and borrows or its shifted partial products, checked against decimal.
Try it: add in binary
Add the two binary numbers.
How many values can bits hold, and what is a byte?
n bits can hold 2^n different values, the numbers from 0 to 2^n-1, because each extra bit doubles the number of patterns. A byte is 8 bits and so holds 2^8=256 values, 0 to 255.
| Bits | Values | Range as unsigned | Common name |
|---|---|---|---|
| 1 | 2 | 0 to 1 | a bit |
| 4 | 16 | 0 to 15 | a nibble, one hex digit |
| 8 | 256 | 0 to 255 | a byte |
| 16 | 65,536 | 0 to 65,535 | a short |
| 32 | 4,294,967,296 | 0 to 4,294,967,295 | an int in many languages |
| 64 | 18,446,744,073,709,551,616 | 0 to 18,446,744,073,709,551,615 | a long |
Sizes. A kilobyte (kB) is 1000 bytes in the SI system, but memory comes in powers of 2, so in 1998 the IEC named the binary units: a kibibyte (KiB) is 2^10=1024 bytes, a mebibyte (MiB) is 2^20=1,048,576 bytes and a gibibyte (GiB) is 2^30 bytes. A disc sold as 500 GB (powers of 1000) shows up as about 465 GiB in an operating system that counts in powers of 1024, which is the usual source of "missing" space.
Text. A character is stored as a number. ASCII, from 1963, assigns the codes 0 to 127 to English letters, digits, punctuation and control codes, and fits in 7 bits. The letter A is 65, which is 01000001_2, and a is 97, which is 01100001_2. The two differ in exactly one bit, the one worth 32, so changing the case of an ASCII letter is flipping that bit. Unicode extends the idea to all writing systems, and UTF-8 stores each code point in 1 to 4 bytes.
Click the bits of a byte below and watch the number, its two readings and the character change.
Interactive: flip the bits of a byte
Click individual bits and read the number as unsigned, as signed two’s complement, in hexadecimal and octal, and as an ASCII character.
Try it: how many values?
How many different values can 10 bits hold?
- 100
- 512
- 1024
- 2048
How are negative numbers stored in binary?
Computers store negative integers in two's complement: the leftmost bit counts as -2^n-1 instead of +2^n-1, so the same addition circuit works for positive and negative numbers. To negate a number, invert every bit and add 1.
For 8 bits, to get -5: start with 5=00000101, invert to 11111010, and add 1 to get 11111011. Read it with the top bit worth -128: -128+64+32+16+8+2+1=-5.
| 8-bit pattern | Unsigned | Signed |
|---|---|---|
| 00000000 | 0 | 0 |
| 00000001 | 1 | 1 |
| 01111111 | 127 | 127 |
| 10000000 | 128 | −128 |
| 11111110 | 254 | −2 |
| 11111111 | 255 | −1 |
With n bits the signed range is -2^n-1 to 2^n-1-1, so 8 bits hold −128 to 127 and 32 bits hold −2,147,483,648 to 2,147,483,647. There is one more negative number than positive because 0 uses one of the non-negative patterns.
Why this scheme. Older ideas, such as a separate sign bit, give two zeros (+0 and −0) and need special rules for adding. In two's complement there is one zero, and subtraction is addition: 5+(-5)=00000101+11111011=100000000, and the ninth bit is discarded, leaving 0. A hardware adder needs no sign logic.
Overflow. A result that does not fit wraps around. In 8 bits 127+1=01111111+00000001=10000000, which reads as −128. Fixed-size integers in C and Java wrap like this (see the integers in code section), while Python integers grow as large as memory allows, so Python only shows the wrapping when you mask the bits yourself.
Try the ×2, +1 and NOT buttons on the bit editor above to see the wrap.
Try it: negate a number
Write -5 in 8-bit two’s complement.
Try it: read a signed byte
What number is 11111110 in 8-bit two’s complement?
- -2
- 254
- -126
- -1
What are bitwise operators and shifts?
Bitwise operators work on each bit of a number separately: AND keeps a 1 only where both bits are 1, OR gives 1 where either bit is 1, XOR gives 1 where the bits differ, and NOT flips every bit. Shifts slide all the bits left or right.
| Bits | AND | OR | XOR |
|---|---|---|---|
| 0, 0 | 0 | 0 | 0 |
| 0, 1 | 0 | 1 | 1 |
| 1, 0 | 0 | 1 | 1 |
| 1, 1 | 1 | 1 | 0 |
For example 1100_2 AND 1010_2 is 1000_2, so 12 \& 10=8; OR gives 1110_2=14 and XOR gives 0110_2=6.
What they are for.
- Masks.
x & 0xFFkeeps the lowest byte, andx & 1is 1 exactly when x is odd. - Flags. Several yes-or-no settings fit in one number, one bit each: set a flag with OR, clear it with AND and NOT, toggle it with XOR. Unix file permissions are three such flags per group.
- Shifts. Shifting left by k multiplies by 2^k and shifting right by k divides by 2^k, dropping the remainder, which is the doubling and halving seen earlier. Bits pushed past the end are lost.
- Tricks. x \& (x-1) is 0 exactly when x is a power of 2 (or 0), and x XOR x is always 0.
Mixing operators with ordinary arithmetic needs care about the order of operations, as with negative numbers in the integers article: put brackets round bitwise expressions. Try the operators on two bytes below.
Interactive: AND, OR, XOR, NOT and shifts
Apply a bitwise operator to two bytes and see the bits line up, with the result in binary and in decimal.
Try it: bitwise AND
What is 12 \& 10 (bitwise AND)?
- 14
- 8
- 6
- 2
How are fractions written in binary?
After the binary point the places are worth \frac12,\frac14,\frac18,…, so a fraction terminates in binary only when its denominator, in lowest terms, is a power of 2. For example 0.101_2=\frac12+\frac18=\frac58=0.625.
The reason is the rule for decimals applied to base 2. A fraction in lowest terms terminates in base b exactly when every prime factor of its denominator divides b: in base 10 the primes 2 and 5, as in the fractions to decimals section, and in base 2 only the prime 2. So:
| Fraction | Binary | Terminates? |
|---|---|---|
| \frac12 | 0.1 | yes |
| \frac38 | 0.011 | yes |
| 5/4 | 1.01 | yes |
| \frac13 | 0.(01 repeating) | no: repeats |
| \frac110 | 0.0(0011 repeating) | no: repeats |
| \frac15 | 0.(0011 repeating) | no: repeats |
To find the digits, multiply the fractional part by 2: the whole part is the next bit, and the rest is carried on. 0.1→0.2→0.4→0.8→1.6 gives bit 0, 0, 0, 1 and continues with 0.6, 1.2, 0.4, so the block 0011 repeats for ever.
Why this matters for programs. A floating-point number stores a fixed number of significant bits, 53 in the common 64-bit format (IEEE 754 binary64), as a sign, an exponent and a fraction. So only fractions with a power of 2 as denominator, such as 0.5, 0.25, 0.75 and 0.125, are held exactly. Numbers such as 0.1, 0.2 and 0.3 are cut off in the middle of their repeating block, and the nearest stored value is used instead. That is why 0.1 + 0.2 is 0.30000000000000004, described in the real numbers article. The cure is to compare with a tolerance, or to count in whole units such as cents.
Type any number below and see its expansion in binary, octal or hexadecimal.
Interactive: fractions in binary
Write a number such as 0.1 in binary, octal or hexadecimal and see whether it terminates or repeats, and the long multiplication that gives the digits.
Try it: a binary fraction
Find a.
How do you work with binary numbers in Python and JavaScript?
Both languages write binary literals with 0b, convert with bin and int(text, 2) in Python or toString(2) and parseInt(text, 2) in JavaScript, and share the bitwise operators &, |, ^, ~, << and >>. They differ on integer size: Python integers have no limit, while JavaScript's bitwise operators silently work on 32-bit signed integers.
>>> bin(10), bin(255), hex(255), oct(64)
('0b1010', '0b11111111', '0xff', '0o100')
>>> int('1011010', 2), int('ff', 16), 0b1011010
(90, 255, 90)
>>> f'{90:08b}', f'{255:#x}', format(5, '04b') # padded binary, hex, width
('01011010', '0xff', '0101')
>>> (255).bit_length()
8
>>> 0b1100 & 0b1010, 0b1100 | 0b1010, 0b1100 ^ 0b1010
(8, 14, 6)
>>> 1 << 4, 100 >> 2 # times 16, divide by 4
(16, 25)
>>> ~5 # NOT: -x - 1
-6
>>> bin(-5) # a sign, not two's complement
'-0b101'
>>> (-5) & 0xFF # the low 8 bits of -5
251
>>> 2 ** 64 # no overflow
18446744073709551616
>>> (0.1).hex() # the stored binary value of 0.1
'0x1.999999999999ap-4'(10).toString(2) // '1010'
(255).toString(16) // 'ff'
parseInt('1011010', 2) // 90
0b1011010 // 90
5 & 3, 5 | 3, 5 ^ 3 // 1, 7, 6
~5 // -6
1 << 31 // -2147483648: bitwise operators use 32-bit signed integers
(1 << 31) >>> 0 // 2147483648: >>> reads the 32 bits as unsigned
-5 >>> 0 // 4294967291
(-5 >>> 0).toString(2) // '11111111111111111111111111111011': two's complement in 32 bits
2 ** 32 >> 0 // 0: the high bits are discarded
2n ** 64n // 18446744073709551616n (BigInt has no 32-bit limit)#include <iostream>
#include <cstdio>
using namespace std;
void printBinary(int n, int width) { // the lowest `width` bits, high bit first
for (int i = width - 1; i >= 0; i--) cout << ((n >> i) & 1);
cout << endl;
}
int parseBinary(const char* s) { // "1011010" -> 90
int value = 0;
for (int i = 0; s[i] != 0; i++) value = value * 2 + (s[i] - '0');
return value;
}
int main() {
printBinary(90, 8);
printBinary(255, 8);
printf("%x %o\n", 255, 64); // hexadecimal and octal
cout << parseBinary("1011010") << endl;
cout << (12 & 10) << " " << (12 | 10) << " " << (12 ^ 10) << endl; // AND, OR, XOR
cout << (1 << 4) << " " << (100 >> 2) << endl; // times 16, divide by 4
cout << ~5 << endl; // NOT: -x - 1
printBinary(-5, 8); // the low 8 bits of -5 (two's complement)
cout << ((-5) & 0xFF) << endl;
return 0;
}
/* output:
01011010
11111111
ff 100
90
8 14 6
16 25
-6
11111011
251
*/The pitfalls, in order of how often they bite:
| Pitfall | What happens | What to do |
|---|---|---|
~5 | gives −6, not −5 | NOT is −x − 1; negate with -x |
bin(-5) or (-5).toString(2) | a minus sign and the bits of 5 | mask with & 0xFF (Python) or use >>> 0 (JavaScript) to see two's complement |
| Bitwise operators in JavaScript | work on 32 bits: 2 ** 32 >> 0 is 0 | use BigInt for larger values |
1 << 31 in JavaScript | negative | add >>> 0 when you want unsigned |
| Shift count too large | JavaScript uses the count modulo 32: 1 << 32 is 1 | keep the count below the width |
| Precedence | x & 1 == 0 means x & (1 == 0) in many languages | add brackets: (x & 1) == 0 |
| Binary fractions | 0.1 + 0.2 != 0.3 | compare with a tolerance |
Use int(text, 2) or parseInt(text, 2) to read binary typed by a person, and format with f'{n:08b}' or n.toString(2).padStart(8, '0') to line the bits up.
Where does binary come from?
Binary arithmetic is much older than computers: Indian, Egyptian and European thinkers used it long before electronics made it essential.
- c. 200 BCE. Pingala, in a Sanskrit work on poetic meter, described patterns of short and long syllables that amount to binary numbers.
- Egypt. The Rhind Papyrus multiplies by repeated doubling and adding, which is multiplication by the binary digits of one number.
- 1703. Leibniz published Explication de l'arithmétique binaire. He saw in the hexagrams of the I Ching, which are six-line patterns of broken and unbroken lines, the numbers 0 to 63 in binary.
- 1854. George Boole's Laws of Thought made logic an algebra of true and false, 1 and 0.
- 1937. Claude Shannon showed in his master's thesis that relay switches can carry out Boolean logic, the link between algebra and circuits. In 1948 he made the word bit, suggested by John Tukey, the unit of information.
- 1963. ASCII gave letters and symbols standard 7-bit codes.
One theme runs through all of them: two symbols are enough to write any number, and any decision between two options can be recorded as a single bit.
What are the common mistakes with binary numbers?
The most common mistakes with binary numbers are the nine below, each with the correct statement and a number that shows why.
| Mistake | Correct |
|---|---|
| ❌ 1+1=2 in binary | There is no digit 2 in binary: 1+1=10_2. |
| ❌ 10_2 is ten | 10_2 is two; ten is 1010_2. |
| ❌ A byte is 4 bits | A byte is 8 bits; 4 bits are a nibble. |
| ❌ A byte holds 255 values | It holds 256 values, 0 to 255. |
❌ ~5 is −5 | ~5=-6: NOT is -x-1. |
| ❌ Binary cannot show negative numbers | Two's complement does: 11111011_2=-5 in 8 bits. |
| ❌ 11111111_2 is always 255 | Unsigned it is 255; as signed 8-bit it is −1. |
| ❌ 1 KB is always 1024 bytes | kB is 1000 bytes; KiB is 1024 bytes. |
| ❌ 0.1 is stored exactly in binary | 0.1=0.0(0011 repeating)_2 repeats, so a float holds only the nearest value. |
Practice: test your understanding
These questions mix everything above. A wrong answer costs nothing here: read the hint and try again.
True or false?
Decide whether each statement is True or False.
- 1+1=10 in binary.
- 1000_2 is eight.
- A byte can hold 255 different values.
- In 8-bit two’s complement, 11111111 is 255.
- 0.1 can be written exactly with finitely many binary digits.
Select all that apply
Choose all the numbers equal to twelve.
- 1100_2
- 14_8
- C_16
- 1010_2
- 20_8
A carry that runs through
Add.
Hexadecimal to decimal
Convert to decimal.
Minus one
Which 8-bit pattern is -1 in two’s complement?
- 10000001
- 10000000
- 01111111
- 11111111
An odd test
Which expression is true exactly when x is odd?
- x \& 2=1
- x≫1=1
- x \& 1=1
- x⊕ x=1
Summary: binary numbers at a glance
- Binary: base 2, digits 0 and 1 (bits), places worth 1,2,4,8,…; 1011_2=11.
- Converting: add the powers of 2 under the 1s; divide by 2 and read the remainders upward; four bits make one hex digit, three one octal digit.
- Arithmetic: 1+1=10 with a carry; multiply by shifting and adding; appending 0 doubles.
- Size: n bits hold 2^n values, a byte is 8 bits (256 values); KiB is 1024 bytes, kB is 1000.
- Negatives: two's complement, the top bit is -2^n-1; negate by inverting and adding 1; overflow wraps.
- Bitwise: AND masks, OR sets, XOR flips; x≪ k is x·2^k; x \& 1 tests odd.
- Fractions: places \frac12,\frac14,…; terminates only for denominators that are powers of 2, so 0.1 repeats and floats approximate it.
- Code:
bin,int(s, 2),toString(2); JavaScript bitwise operators are 32-bit;~xis-x - 1.
Glossary: key terms
- Bit
- A binary digit, 0 or 1, the smallest unit of information; the word is short for binary digit.
- Byte
- A group of 8 bits, which can hold 256 different values, 0 to 255 when read as unsigned.
- Binary number
- A number written in base 2 with only the digits 0 and 1, each place worth a power of 2.
- Place value
- The principle that a digit is worth its face value times the power of the base for the place it stands in.
- Hexadecimal
- Base 16, with digits 0 to 9 and A to F; one hex digit is exactly four bits, so a byte is two hex digits.
- Octal
- Base 8, with digits 0 to 7; one octal digit is exactly three bits.
- Nibble
- A group of four bits, which is one hexadecimal digit.
- Most significant bit
- The leftmost bit of a binary number, the one in the highest place; in two’s complement it is the sign bit.
- Two’s complement
- The usual way to store negative integers, where the leftmost bit is worth minus 2 to the power n minus 1 and a number is negated by inverting its bits and adding 1.
- Overflow
- The wrapping around that happens when a result does not fit in the fixed number of bits, as 127 plus 1 becomes minus 128 in 8 bits.
- Bitwise operator
- An operator such as AND, OR, XOR or NOT that works on each bit of its operands separately.
- Bit shift
- An operation that slides all the bits left or right; shifting left by k multiplies by 2 to the power k.
- Bit mask
- A number whose 1 bits select which bits of another number to keep, change or test, used with AND, OR and XOR.
- Kibibyte
- The binary unit equal to 1024 bytes, written KiB, to tell it from the kilobyte of 1000 bytes.
- ASCII
- A 1963 standard that gives English letters, digits, punctuation and control characters the codes 0 to 127.
- Floating-point number
- A number stored as a sign, an exponent and a fixed number of significant bits, so most fractions are held only approximately.
Frequently asked questions
What is a binary number?
A binary number is a number written in base 2, using only the digits 0 and 1. Each place is worth twice the place to its right, so 1011 in binary is 8 plus 2 plus 1, which is 11. Each digit is called a bit.
Why do computers use binary?
Electronic parts such as transistors have two reliable states, on and off, and two states are easy to tell apart even with noise. Machines can therefore copy and process binary signals without errors. Every number, letter and image is first turned into bits.
How do you convert binary to decimal?
Write the place values 1, 2, 4, 8 and so on from the right, and add the ones that sit under a 1. For 1011010 these are 64, 16, 8 and 2, which add up to 90. Each place is a power of 2.
How do you convert decimal to binary?
Divide the number by 2 repeatedly, writing down each remainder, until the quotient is 0. Then read the remainders from the last to the first. For 45 the remainders read upward are 101101, and 32 plus 8 plus 4 plus 1 is 45.
What is hexadecimal and why is it used?
Hexadecimal is base 16, with digits 0 to 9 and A to F. One hex digit is exactly four bits, so a byte is two hex digits and long binary strings become short. Web colors such as FF8800 and memory addresses are written in hexadecimal.
What is the difference between a bit and a byte?
A bit is a single binary digit, 0 or 1. A byte is a group of 8 bits, which can hold 256 different values from 0 to 255. Four bits are called a nibble, and one hexadecimal digit is a nibble.
How many values can n bits store?
Exactly 2 to the power n, because each extra bit doubles the number of patterns. As unsigned numbers they run from 0 to 2 to the power n minus 1. So 8 bits store 256 values, 16 bits store 65,536 and 32 bits store about 4.3 billion.
How are negative numbers stored in binary?
Almost all computers use two’s complement. The leftmost bit is worth minus 2 to the power n minus 1, so in 8 bits 10000000 is minus 128 and 11111111 is minus 1. To negate a number, invert every bit and add 1, which makes subtraction an ordinary addition.
What is integer overflow?
It is what happens when a result does not fit in the fixed number of bits. The value wraps around: in 8-bit signed arithmetic 127 plus 1 gives minus 128. In C and Java this is a real hazard, while Python integers grow as large as memory allows.
What is 1 plus 1 in binary?
It is 10 in binary, which is read one-zero and means two. There is no digit 2 in base 2, so the sum is written as 0 with a carry of 1 into the next place, just as 5 plus 5 is written as 0 with a carry in decimal.
What do AND, OR and XOR do to bits?
They combine two numbers bit by bit. AND gives 1 only where both bits are 1, OR gives 1 where at least one is 1, and XOR gives 1 where the bits differ. NOT flips every bit. They are used for masks, flags and quick tests such as whether a number is odd.
What does shifting bits do?
Shifting left by k places multiplies a number by 2 to the power k, and shifting right by k places divides by 2 to the power k and drops the remainder. It works like adding or removing zeros in decimal. Bits pushed past the end of the number are lost.
Why is 0.1 not stored exactly in binary?
A fraction terminates in binary only if its denominator is a power of 2. One tenth has the factor 5, so its binary expansion 0.000110011 and so on repeats for ever. A float keeps only 53 significant bits, so it stores the nearest value, and 0.1 plus 0.2 is slightly more than 0.3.
How do you work with binary in Python?
Write literals with the prefix 0b, convert a number with bin, hex and format, and read text with int and a base such as 2. The operators are the ampersand, the bar, the caret, the tilde and the two shifts. Python integers have no fixed size, so the tilde of 5 is minus 6.
References
- James Stewart, Lothar Redlin and Saleem Watson (2016). Precalculus: Mathematics for Calculus (7th ed.). Cengage Learning.
- Donald E. Knuth (1997). The Art of Computer Programming, volume 2: Seminumerical Algorithms (3rd ed.), section 4.1 (positional number systems). Addison-Wesley.
- Gottfried Wilhelm Leibniz (1703). Explication de l’arithmétique binaire. Mémoires de l’Académie royale des sciences.
- George Boole (1854). An Investigation of the Laws of Thought.
- Claude E. Shannon (1938). A Symbolic Analysis of Relay and Switching Circuits. Transactions of the American Institute of Electrical Engineers 57, 713–723.
- IEEE (2019). IEEE Standard for Floating-Point Arithmetic (IEEE 754-2019). Institute of Electrical and Electronics Engineers.
- International Electrotechnical Commission (2008). IEC 80000-13:2008, Quantities and units, Part 13: Information science and technology (binary prefixes kibi, mebi, gibi).
- Python Software Foundation. The Python Standard Library: bitwise operations on integer types. docs.python.org. https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types.
Related articles
- Integers: Number Line, Operations, Divisibility, GCD and LCM: Integers explained: the number line, adding and multiplying negatives, divisibility, primes, GCD and LCM, and remainders, with worked examples and practice.
- Rational Numbers: Fractions, Operations, Decimals and Percent: Rational numbers explained: fractions, equivalent forms, comparing, the four operations, mixed numbers, decimals and percent, with worked examples and practice.
- Real Numbers: Definition, Types, Examples and Properties: Real numbers explained: definition, types (rational and irrational), examples, properties and the number line, with interactive practice, a proof and FAQ.
- Exponents and Radicals: Laws, Rules, Examples and Practice: Exponents and radicals explained: the five laws, zero, negative and fractional exponents, simplifying roots, rationalizing and scientific notation, with practice.