Conceptcore
Bits, bytes and bitwise operations
Also called bit, byte, bitwise operation, bit mask, bit flags, shift, logical shift, arithmetic shift, endianness, byte order, hexadecimal.
Every value is stored as bits, grouped into bytes and words. Bitwise operators test, set, clear and shift the bits of an integer, and a byte order fixes how wide numbers become bytes.
- Applies to
- core-languages
Idea
A computer stores every value as bits, each a 0 or a 1. A byte is 8 bits and holds one of 256 patterns, and a machine word is 4 or 8 bytes. The meaning of a pattern depends on the type that reads it: the byte 10110110 is 182 as an unsigned number, -74 as a signed one, and part of a character in UTF-8. Bitwise operators work on the bits of an integer directly. AND keeps bits, OR sets them, XOR flips them, NOT inverts all of them, and shifts move them left or right. Programs use these operators for flags, masks, hashes, compression, graphics, network protocols and file formats, and to put multi-byte numbers into bytes in a fixed order.
x, m = 0b1011_0110, 0b0000_1111
def show(label, v):
print(f"{label:<10} {v & 0xFF:08b} {v & 0xFF:3} 0x{v & 0xFF:02X}")
show("x", x)
show("m", m)
show("x & m", x & m) # keep the bits that are 1 in m
show("x | m", x | m) # set the bits of m
show("x ^ m", x ^ m) # flip the bits of m
show("~x", ~x) # flip every bit
show("x << 2", x << 2) # bits move left, zeros come in
show("x >> 2", x >> 2) # bits move right, low bits drop
n = 0x12345678
print("big-endian bytes ", n.to_bytes(4, "big").hex(" "))
print("little-endian bytes", n.to_bytes(4, "little").hex(" "))
x 10110110 182 0xB6
m 00001111 15 0x0F
x & m 00000110 6 0x06
x | m 10111111 191 0xBF
x ^ m 10111001 185 0xB9
~x 01001001 73 0x49
x << 2 11011000 216 0xD8
x >> 2 00101101 45 0x2D
big-endian bytes 12 34 56 78
little-endian bytes 78 56 34 12
Each row shows a result as 8 bits, in decimal and in hexadecimal. The mask m has 1 bits in its low four places, so x & m keeps the low four bits of x, x | m sets them, and x ^ m flips them. ~x flips all eight. A left shift by 2 multiplies by 4 and drops the bits that move past the eighth place, and a right shift by 2 divides by 4 and drops the low bits. The last two lines store the 32-bit number 0x12345678 as 4 bytes: big-endian order puts the most significant byte first, and little-endian order puts it last.
How it works
Binary and hexadecimal. A number in base 2 has one digit for each bit, and bit i has the value 2 to the power i. Binary numbers are long, so programmers write them in hexadecimal, where each digit stands for exactly 4 bits: 0xB6 is 1011 0110. Most languages accept literals in both bases, such as 0b1011_0110 and 0xB6, with underscores or quotes to group the digits. Octal, with 3 bits for each digit, survives in Unix file permissions such as 0o755.
AND, OR, XOR and NOT. The bitwise operators apply a logic function to each pair of bits at the same position. AND gives 1 where both bits are 1, OR where at least one is 1, and XOR where exactly one is 1. NOT flips each bit. With a mask, a value with 1 bits at the positions of interest, these give the four basic operations on a set of flags: test a bit with x & m, set it with x | m, clear it with x & ~m and toggle it with x ^ m. Go has a separate operator for the third, x &^ m. XOR has two useful properties: x ^ x is 0, and applying the same mask twice gives the original value back, which hashes, checksums and simple ciphers use.
Shifts. A left shift moves every bit toward the high end and puts zeros in the low positions, which multiplies by a power of two. A right shift moves bits toward the low end, and there are two kinds. A logical shift puts zeros in the high positions. An arithmetic shift copies the sign bit, so that a negative number stays negative and the result is a division by a power of two, rounded down. The C# documentation says that for int and long "the right-shift operator performs an arithmetic shift: the value of the most significant bit (the sign bit) of the left-hand operand is propagated to the high-order empty bit positions."1 Java, JavaScript and C# give the logical right shift its own operator, >>>. Go and Rust choose by the type: "The shift operators implement arithmetic shifts if the left operand is a signed integer and logical shifts if it is an unsigned integer."2
Width. Bitwise results depend on the number of bits in the type, and languages handle the edges differently. In C and C++, a shift by a count at or above the width has no defined result: "If the value of rhs is negative or is not less than the number of bits in lhs, the behavior is undefined."3 Java takes the count modulo the width: for an int, "only the five lowest-order bits of the right-hand operand are used as the shift distance".4 Go defines the result instead: "There is no upper limit on the shift count."2 Rust counts a shift at or above the width as overflow, with "Using << or >> where the right-hand argument is greater than or equal to the number of bits in the type of the left-hand argument, or is negative" in its list of overflows, and "Integer operators will panic when they overflow when compiled in debug mode."5 JavaScript numbers are floating point, so its operators first convert to 32 bits: "A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers."6 Python integers have no width at all: "The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits."7
Byte order. A number wider than one byte has to be stored as several bytes, and machines disagree on their order. Big-endian machines store the most significant byte at the lowest address, and little-endian machines store the least significant byte there. Danny Cohen named the two camps in 1980, after the egg war in Gulliver's Travels: "This is an attempt to stop a war."8 He described the question as "which bit should travel first, the bit from the little end of the word, or the bit from the big end of the word?"8 Today x86 and most ARM systems are little-endian, while network protocols send numbers in big-endian order, which is also called network byte order. Code that reads or writes bytes for a file or a network states the order, with functions such as to_le_bytes, binary.BigEndian or DataView, or builds the bytes with shifts and masks. Then the result does not depend on the machine.
Bit tricks. Many small algorithms work on whole words at once. x & (x - 1) clears the lowest set bit, so a loop of it counts the 1 bits. x & -x isolates the lowest set bit. x != 0 && (x & (x - 1)) == 0 tests for a power of two. A word of 64 bits can hold a set of 64 small integers, and AND, OR and XOR then compute intersection, union and symmetric difference in one instruction. Modern processors have instructions to count bits, count leading and trailing zeros, and rotate, and languages expose them as bit_count, popcount, leading_zeros and rotl.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | As JavaScript; the operators work on 32-bit integers, and bigint has the same operators with no fixed width. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | The infix functions and, or, xor, shl, shr and ushr and the function inv work on Int and Long; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Native | Most dialects have bitwise operators on integers and bit string types, though the SQL standard does not define the operators. |
| Bash | Native | Arithmetic expansion has the C operators on 64-bit signed integers, as in $(( flags & 4 )). |
| PowerShell | Native | The operators -band, -bor, -bxor, -bnot, -shl and -shr work on .NET integers and flags enums; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup has no values to operate on. |
| CSS | Does not apply | Style sheets have no bit operations. |
| Regular expressions | Does not apply | Patterns match characters, not bits. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | operators on int of any width; to_bytes, struct |
| JavaScript | native | operators on 32-bit integers; >>>; BigInt; DataView |
| TypeScript | native | as JavaScript |
| Java | native | operators on int and long; >>>; ByteBuffer |
| Kotlin | native | infix functions and, or, xor, shl, shr, ushr |
| C# | native | operators; >>>; [Flags] enums; BinaryPrimitives |
| Go | native | operators with &^; math/bits; encoding/binary |
| Rust | native | operators with !; checked and wrapping shifts; byte methods |
| C | native | operators on integers; unsigned types for bit patterns |
| C++ | native | the operators of C; <bit>; std::bitset |
| Bash | native | operators in arithmetic expansion |
| PowerShell | native | -band, -bor, -bxor, -bnot, -shl, -shr |
| SQL | native | dialect operators on integers; bit string types |
| Regex | n/a | patterns match characters, not bits |
| HTML | n/a | no values to operate on |
| CSS | n/a | no values to operate on |
Every example file does the same work: it keeps a set of three permission flags, clears one and toggles another, counts the 1 bits, shifts negative numbers, and writes 0x12345678 as little-endian bytes. The operators are almost the same in every language, because most of them come from C. The differences are at the edges: what happens to a shift count past the width, whether >> keeps the sign, whether a byte is signed, and how wide the integers are.
Three groups appear. C, C++, Java, C#, Go and Rust have integer types of fixed widths, so a bit pattern has a known size, and the language defines or forbids what happens past it. JavaScript has one number type and converts to 32 bits for each bitwise operation, with BigInt for wider patterns. Python has integers of any width, so masks must state the width that a result needs.
import struct
READ, WRITE, EXEC = 1 << 0, 1 << 1, 1 << 2
perm = READ | WRITE
print(bool(perm & WRITE), bool(perm & EXEC)) # test a bit
perm &= ~WRITE # clear a bit
perm ^= EXEC # toggle a bit
print(f"{perm:03b}", perm.bit_count(), perm.bit_length())
print(~5, -8 >> 1, -1 & 0xFF) # as if there were infinite sign bits
print(1 << 100) # ints have no fixed width
n = 0x12345678
print(n.to_bytes(4, "little").hex(), struct.pack(">I", n).hex())
print(hex(int.from_bytes(b"\x78\x56\x34\x12", "little")))
True False
101 2 3
-6 -4 255
1267650600228229401496703205376
78563412 12345678
0x12345678
This code runs but gives a wrong answer on purpose.
b = 0b0000_1111
inverted = ~b # meant to flip the 8 bits of a byte
print(inverted, f"{inverted:b}")
try:
bytes([inverted])
except ValueError as e:
print(e)
print(~b & 0xFF) # mask to the width you mean
-16 -10000
bytes must be in range(0, 256)
240
- Verdict: native. Python has the operators
&,|,^,~,<<and>>onint, andbin,hexand format specs such as:08bto print bits. Aninthas no fixed width, so the operators behave as if a negative number had an infinite row of 1 bits on the left:~5is-6and-8 >> 1is-4.bit_countandbit_lengthcount bits, andint.to_bytes,int.from_bytesand thestructmodule convert between integers and bytes in a stated byte order. - The wrong block flips the bits of a byte with
~. With no fixed width, the result is the negative number-16, not240, andbytesrejects it. Mask the result to the width you mean, as with& 0xFF.
#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
enum Perm : std::uint8_t { Read = 1 << 0, Write = 1 << 1, Exec = 1 << 2 };
int main() {
std::uint8_t perm = Read | Write;
perm &= ~Write;
perm ^= Exec;
std::cout << std::bitset<3>(perm) << ' ' << std::popcount(perm) << '\n';
std::uint8_t b = 0b1001'0110;
std::cout << int(std::rotl(b, 1)) << ' ' << std::countl_zero(std::uint32_t{1})
<< ' ' << std::has_single_bit(64u) << ' ' << std::bit_width(255u) << '\n';
std::cout << (-8 >> 1) << ' ' << (0xF0u >> 4) << ' '
<< (std::endian::native == std::endian::little ? "little" : "big") << '\n';
float f = 1.0f;
std::cout << std::hex << std::bit_cast<std::uint32_t>(f) << '\n';
}
101 2
45 31 1 8
-4 15 little
3f800000
- Verdict: native. C++ has the operators of C and the header
<bit>withpopcount,rotl,countl_zero,has_single_bit,bit_width,bit_castandendian.std::bitsetholds a fixed number of bits and prints them. Right shift of a negative value is arithmetic, and the rules for undefined shift counts are the same as in C. std::bit_castcopies the bits of one type into another type of the same size, here the bits of thefloat1.0, without the undefined behavior of a cast between pointer types.
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HexFormat;
public class Main {
static final int READ = 1, WRITE = 1 << 1, EXEC = 1 << 2;
public static void main(String[] args) {
int perm = READ | WRITE;
perm &= ~WRITE;
perm ^= EXEC;
System.out.println(Integer.toBinaryString(perm) + " " + Integer.bitCount(perm));
System.out.println((-8 >> 1) + " " + (-8 >>> 28) + " " + (1 << 32) + " " + (1L << 32));
byte b = (byte) 0xF0; // byte is signed
System.out.println(b + " " + (b & 0xFF) + " " + Integer.toHexString(b));
byte[] le = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(0x12345678).array();
System.out.println(HexFormat.of().formatHex(le) + " " + Integer.toHexString(Integer.reverseBytes(0x12345678)));
}
}
101 2
-4 15 1 4294967296
-16 240 fffffff0
78563412 78563412
- Verdict: native. Java has
&,|,^,~,<<, the arithmetic right shift>>and the logical right shift>>>onintandlong. A shift of anintuses only the low 5 bits of the count, so1 << 32is1, and a shift of alonguses the low 6 bits.IntegerandLonghavebitCount,toBinaryString,reverseBytesand other bit methods. - Java's
byteis signed, so(byte) 0xF0is-16and widens to0xFFFFFFF0. Mask with& 0xFFto read a byte as a number from 0 to 255.ByteBufferreads and writes in big-endian order by default, andorderchanges it.
#include <stdint.h>
#include <stdio.h>
enum { READ = 1u << 0, WRITE = 1u << 1, EXEC = 1u << 2 };
static int popcount(uint32_t x) {
int n = 0;
for (; x != 0; x &= x - 1) /* clear the lowest set bit */
n++;
return n;
}
int main(void) {
unsigned perm = READ | WRITE;
perm &= ~(unsigned)WRITE;
perm ^= EXEC;
printf("%u %d %d\n", perm, popcount(perm), (perm & EXEC) != 0);
uint32_t x = 0x12345678;
uint8_t le[4];
for (int i = 0; i < 4; i++)
le[i] = (uint8_t)(x >> (8 * i)); /* least significant byte first */
printf("%02x %02x %02x %02x\n", le[0], le[1], le[2], le[3]);
uint32_t back = (uint32_t)le[0] << 24 | (uint32_t)le[1] << 16 | (uint32_t)le[2] << 8 | le[3];
printf("%08x %u\n", (unsigned)back, 0xF0u >> 4);
return 0;
}
5 2 1
78 56 34 12
78563412 15
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
enum { READ = 1, WRITE = 2 };
int main(void) {
unsigned perm = READ; /* no write permission */
if (perm & WRITE == 0) /* parsed as perm & (WRITE == 0) */
printf("read only\n");
else
printf("writable\n");
if ((perm & WRITE) == 0)
printf("read only\n");
return 0;
}
writable
read only
- Verdict: native. C has
&,|,^,~,<<and>>, and the bit operations of most other languages come from it. Use unsigned types for bit patterns: shifting a negative value left, shifting into the sign bit, or shifting by a count at or above the width is undefined behavior, and right shift of a negative value is implementation-defined. Building bytes with shifts and masks, as the example does, gives the same result on every machine, whatever its byte order. - The wrong block writes
perm & WRITE == 0. In C,==binds more tightly than&, so the test isperm & (WRITE == 0), which is always 0. Put parentheses around every bitwise expression inside a comparison. The compiler warns with-Wparentheses.
using System;
using System.Buffers.Binary;
using System.Numerics;
var perm = Perm.Read | Perm.Write;
perm &= ~Perm.Write;
perm ^= Perm.Exec;
Console.WriteLine($"{perm} {perm.HasFlag(Perm.Exec)} {BitOperations.PopCount((uint)perm)}");
Console.WriteLine($"{-8 >> 1} {-8 >>> 28} {1 << 32} {1L << 32}");
Console.WriteLine($"{Convert.ToString(0b1011_0110, 2)} {0xB6:X} {BitOperations.LeadingZeroCount(1u)}");
var buf = new byte[4];
BinaryPrimitives.WriteUInt32LittleEndian(buf, 0x12345678);
Console.WriteLine($"{Convert.ToHexString(buf)} {BitConverter.IsLittleEndian}");
Console.WriteLine($"{BinaryPrimitives.ReadUInt32BigEndian(buf):X8}");
[Flags]
enum Perm { None = 0, Read = 1, Write = 1 << 1, Exec = 1 << 2 }
Read, Exec True 2
-4 15 1 4294967296
10110110 B6 31
78563412 True
78563412
- Verdict: native. C# has
&,|,^,~,<<,>>and the unsigned right shift>>>. As in Java, the shift count of anintuses its low 5 bits. An enum with the[Flags]attribute names a set of bits, prints as a list of names, and supportsHasFlag.BitOperationscounts and finds bits, andBinaryPrimitivesreads and writes integers in a stated byte order. BitConverter.IsLittleEndiantells the byte order of the machine. Code that writes files or network messages usesBinaryPrimitiveswith an explicit order, so the result does not depend on it.
const READ = 1 << 0, WRITE = 1 << 1, EXEC = 1 << 2;
let perm = READ | WRITE;
perm &= ~WRITE;
perm ^= EXEC;
console.log(perm.toString(2).padStart(3, "0"), (perm & EXEC) !== 0);
console.log(1 << 31, (1 << 31) >>> 0, -8 >> 1, -8 >>> 28);
console.log(1 << 32, Math.clz32(1)); // the shift count is taken mod 32
console.log(1n << 40n, (0xFFn << 56n).toString(16));
const view = new DataView(new ArrayBuffer(4));
view.setUint32(0, 0x12345678, true); // little-endian
console.log(Array.from(new Uint8Array(view.buffer), b => b.toString(16)).join(" "));
console.log(view.getUint32(0, false).toString(16)); // read as big-endian
101 true
-2147483648 2147483648 -4 15
1 31
1099511627776n ff00000000000000
78 56 34 12
78563412
This code runs but gives a wrong answer on purpose.
const ms = 3000000000; // 3e9 milliseconds, about 35 days
const whole = ms | 0; // meant to drop a fraction, as Math.trunc does
console.log(whole, Math.trunc(ms));
console.log((2 ** 53 + 2) & 1, 2 ** 32 + 7 | 0);
-1294967296 3000000000
0 7
- Verdict: native. The bitwise operators of JavaScript convert their operands to 32-bit signed integers, operate, and return a number.
>>>shifts in zeros and gives an unsigned result, sox >>> 0reads the 32 bits as unsigned. The shift count is taken modulo 32, so1 << 32is1. For wider values,BigInthas the same operators with no fixed width.DataViewreads and writes integers in a buffer with a stated byte order. - The wrong block uses
x | 0to drop the fraction of a number, a common trick. It works only for values that fit in 32 bits: 3 billion becomes a negative number, and the low bits of larger numbers vanish. UseMath.truncfor numbers andBigIntfor wide bit patterns.
package main
import (
"encoding/binary"
"fmt"
"math/bits"
)
const (
Read = 1 << iota
Write
Exec
)
func main() {
perm := Read | Write
perm &^= Write // AND NOT clears the bits of Write
perm ^= Exec
fmt.Printf("%03b %d\n", perm, bits.OnesCount(uint(perm)))
var s uint = 40
var u uint32 = 1
fmt.Println(-8>>1, u<<s, bits.LeadingZeros32(u), bits.RotateLeft8(0b1001_0110, 1))
buf := make([]byte, 4)
binary.LittleEndian.PutUint32(buf, 0x12345678)
fmt.Printf("% x %x\n", buf, binary.BigEndian.Uint32(buf))
fmt.Printf("%#x\n", bits.ReverseBytes32(0x12345678))
}
101 2
-4 0 31 45
78 56 34 12 78563412
0x78563412
- Verdict: native. Go has
&,|,^,<<,>>and the AND NOT operator&^, which clears the bits of its right operand. Unary^is bitwise NOT. A right shift is arithmetic for signed integers and logical for unsigned ones, and a shift count at or above the width gives 0, not an error.iotanumbers the constants of a set of flags. math/bitscounts, rotates and reverses bits, andencoding/binaryreads and writes integers in big-endian or little-endian order.
const READ: u8 = 1;
const WRITE: u8 = 1 << 1;
const EXEC: u8 = 1 << 2;
fn main() {
let mut perm = READ | WRITE;
perm &= !WRITE; // ! is bitwise NOT on integers
perm ^= EXEC;
println!("{perm:03b} {} {}", perm.count_ones(), perm & EXEC != 0);
let n: i32 = -8;
println!("{} {} {}", n >> 1, (n as u32) >> 28, 0b1001_0110u8.rotate_left(1));
println!("{:?} {:?} {}", 1u32.checked_shl(32), 1u32.wrapping_shl(33), 1u32.leading_zeros());
let x: u32 = 0x12345678;
let le = x.to_le_bytes();
println!("{:02x?} {:x}", le, u32::from_be_bytes(le));
}
101 2 true
-4 15 45
None 2 31
[78, 56, 34, 12] 78563412
This code does not compile, on purpose.
fn main() {
let mask: u8 = 1 << 8; // a u8 has bits 0 to 7 only
println!("{mask}");
}
- Verdict: native. Rust has
&,|,^,<<,>>and!, which is bitwise NOT on integers. A right shift is arithmetic for signed types and logical for unsigned ones. A shift count at or above the width is overflow: it panics in a debug build, andchecked_shlandwrapping_shlchoose another result explicitly. Integer types havecount_ones,leading_zeros,rotate_left,to_le_bytes,from_be_bytesand other bit methods. - The fails block shifts a
u8by 8 in a constant expression. The compiler sees the overflow and rejects the program with thearithmetic_overflowlint, which is an error by default.
Variations and related ideas
- Bit sets and bitmaps. An array of words used as a set of small integers, with one bit for each possible member.
std::bitset, Java'sBitSetand database bitmap indexes work this way. - Bit fields. C and C++ structs can give a member a width in bits, and network headers and hardware registers use such layouts. Their order in memory depends on the compiler, so portable code uses shifts and masks.
- Flags enums. C#
[Flags]enums, Rust'sbitflagscrate and theenum.Flagclass of Python give names to the bits of a set of options. - Signed integers. Two's complement represents negative integers so that the same adder works for both signs, and it fixes the result of
~xas-x - 1. See integer overflow. - Floating point. A float is also a pattern of bits, with fields for the sign, the exponent and the fraction.
bit_castin C++ andto_bitsin Rust expose them. See floating-point arithmetic. - Text and binary encodings. UTF-8 uses the high bits of each byte to mark how long a sequence is, and Base64 cuts bytes into groups of 6 bits. See UTF-8 and Base64.
- Parsing integers. Converting text to a number and back is a separate step from storing it in bits. See parse an integer.
Pitfalls
- Precedence of
&and==. In C, C++, Java, JavaScript and C#, comparison binds more tightly than bitwise AND, sox & MASK == 0meansx & (MASK == 0). The wrong block in the C file shows this. Put parentheses around every bitwise expression inside a comparison. Python and Go give&higher precedence than comparison, so the same text works there. - Shifts past the width. A shift by 32 or more on a 32-bit value is undefined in C and C++, takes the count modulo 32 in Java, C# and JavaScript, gives 0 in Go, and panics in a debug build of Rust. The fails block in the Rust file shows the compiler rejecting one. Check the count, or use a wider type.
- Signed values. Right shift of a negative number keeps the sign in most languages, so it does not give the bits that a logical shift would. Java's
byteis signed, so a byte read from a file must be masked with& 0xFF. Use unsigned types, or>>>, for bit patterns. - NOT with no fixed width. In Python,
~xof a positive number is negative. The wrong block in the Python file shows this. Mask the result to the width you mean. - 32-bit conversion in JavaScript.
x | 0and~~xtruncate numbers to 32 bits, so they give wrong results for values above about 2.1 billion. The wrong block in the JavaScript file shows this. UseMath.truncfor numbers, andBigIntfor wide bit patterns. - Byte order taken from the machine. Copying the memory of an integer into a file, or casting a byte pointer to an integer pointer, writes the order of the machine that runs the code, and in C the cast can also break alignment and aliasing rules. State the order and build the bytes with shifts, or use the functions of the standard library.
Cost
AND, OR, XOR, NOT and shifts by a constant take one processor instruction and one cycle on a fixed-width integer. A shift by a variable count also takes one instruction on most processors, plus a mask or a check where the language requires one. Counting bits, counting leading zeros and rotating take one instruction on processors that have them, and a short sequence of operations otherwise. On integers of any width, as in Python and BigInt, each operation takes time in proportion to the number of words in the value, plus the cost of the object. Converting byte order costs one byte-swap instruction for each value, and nothing when the order of the machine matches the format.
History
Gottfried Leibniz described binary arithmetic in 1703. Claude Shannon used the word bit in his 1948 paper on communication, and credited it to John Tukey. Werner Buchholz coined the word byte in 1956, during the design of the IBM Stretch computer, for a group of bits that encodes one character. The IBM System/360, from 1964, fixed the byte at 8 bits and addressed memory by the byte, and most later machines did the same. The System/360 stored numbers in big-endian order, while the DEC PDP-11, from 1970, and later the Intel x86 stored them in little-endian order.
C, from the early 1970s, gave programmers the operators &, |, ^, ~, << and >> on integers, and its precedence for & and | came from B, where they also served as logical operators before && and || existed. Danny Cohen's 1980 note On Holy Wars and a Plea for Peace named the byte order camps big-endian and little-endian.8 Java and JavaScript, both from the mid-1990s, have >>>, because Java has no unsigned types and JavaScript took its operators from Java. C++20 made right shift of negative values arithmetic and added the <bit> header.
References
- Bitwise and shift operators, C# reference, Microsoft Learn, Right-shift operator >>
- The Go Programming Language Specification, Arithmetic operators, Integer operators
- Arithmetic operators, cppreference.com, Built-in bitwise shift operators
- Chapter 15, Expressions, The Java Language Specification, Java SE 25 Edition, 15.19 Shift Operators
- Operator expressions, The Rust Reference, Overflow
- Expressions and operators, MDN Web Docs, Bitwise operators
- Built-in Types, Python documentation, Bitwise Operations on Integer Types
- Danny Cohen, On Holy Wars and a Plea for Peace, IEN 137, 1980, Introduction
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 0ZEXPA Edit this page History Report an error Markdown