Skip to content

Bitwise Functions

Binary operations and conversions.

Bitwise Operations

bitwise_and(a, b)

Bitwise AND.

print bitwise_and(12, 10);  // 8
// 1100 & 1010 = 1000

bitwise_or(a, b)

Bitwise OR.

print bitwise_or(12, 10);  // 14
// 1100 | 1010 = 1110

bitwise_xor(a, b)

Bitwise XOR.

print bitwise_xor(12, 10);  // 6
// 1100 ^ 1010 = 0110

bitwise_not(a)

Bitwise NOT.

print bitwise_not(5);

Shifting

shift_left(value, bits)

Left shift (multiply by 2^bits).

print shift_left(5, 1);  // 10 (5 * 2)
print shift_left(5, 2);  // 20 (5 * 4)
print shift_left(5, 3);  // 40 (5 * 8)

shift_right(value, bits)

Right shift (divide by 2^bits).

print shift_right(20, 1);  // 10 (20 / 2)
print shift_right(20, 2);  // 5  (20 / 4)

Utilities

count_bits(number)

Count set bits (1s).

print count_bits(7);   // 3 (binary: 111)
print count_bits(15);  // 4 (binary: 1111)
print count_bits(8);   // 1 (binary: 1000)

to_binary(number)

Convert to binary string.

print to_binary(10);   // "1010"
print to_binary(255);  // "11111111"
print to_binary(42);   // "101010"

from_binary(string)

Convert binary string to number.

print from_binary("1010");      // 10
print from_binary("11111111");  // 255

to_hex(number)

Convert to hexadecimal string.

print to_hex(255);   // "ff"
print to_hex(16);    // "10"
print to_hex(4095);  // "fff"

from_hex(string)

Convert hex string to number.

print from_hex("ff");   // 255
print from_hex("10");   // 16
print from_hex("fff");  // 4095