[PYTHON] Quotient (truncation) / remainder calculation by bit operation

Bit operations are close to low-level languages, so they are fast in any language. Especially useful for dividing 2 by the nth power.

General (JavaScript)

Quotient: OR operation 0 for a division solution (decimal) (Excess: Use% operator, not bitwise operation)

ex.17 รท 6 quotient and remainder


q = (17/6)|0; //quotient= 2
r = 17%6 //remainder= 5

It's not that fast because it produces decimals in the middle, but it's lighter than Math.floor.

For division by 2 to the nth power (1, 2, 4, 8, 16 ...) (JavaScript, Python)

Trade: n-bit shift to the left AND operation with remainder: (2 ^ n) -1

ex.17/8 quotient and remainder


q = 17>>3; //quotient= 2
r = 17&7; //remainder= 1

By the way

Around the binary


//The number of bytes required to store N bit data
byteLength = 1 + ((N-1)>>3);
//To extract the Nth bit from the beginning of Uint8Array
bitN = uint8array[N>>3] & (1<<(N&7));

Recommended Posts

Quotient (truncation) / remainder calculation by bit operation
Bit operation
Logical operation / bit operation 0
[Scientific / technical calculation by Python] Basic operation of arrays, numpy