Bitwise operations

Bitwise operations

Remember that an integer can be written in decimal, binary or hexadecimal form:

13 (decimal) = 0b1101 = 0xd

> The binString and hexString functions can be used to get the binary and hexadecimal representation of an integer, respectively.

Knowing how to manipulate binary values lets you optimize steps in frequent computations, or handle series of booleans quickly.

What is a binary number

A binary number can represent both a number and an array of boolean values. Since integers are 64 bits wide, you can represent 64 boolean values in a single integer. In what follows, a bit set to 1 stands for a true value, and a bit set to 0 stands for false.

Available operators and functions

The bitwise operators of LeekScript are:

Dedicated functions also make bit-level manipulation easier: testBit, setBit, bitCount, bitLength, trailingZeros and leadingZeros.

To handle integers wider than 64 bits, see BigInteger.

Bit masks

Bit masks are used to retrieve the value of bits or groups of bits of a number.

Retrieving the value of the bit at index N

To retrieve the value at index N:

Retrieving the value of N consecutive bits

To retrieve the value of the last N bits:

Where 0b111...111 is a binary number made of N times the digit 1, hence equivalent to 2**N-1.