Updated on 2024-10-25 GMT+08:00

Bitwise Functions

  • bit_count(x, bits) → bigint

    Calculate the number of bits set in x (regarded as an integer with a signed bit) in the complementary code representation of 2.

    SELECT bit_count(9, 64); -- 2
    SELECT bit_count(9, 8); -- 2
    SELECT bit_count(-7, 64); -- 62
    SELECT bit_count(-7, 8); -- 6
  • bitwise_and(x, y) → bigint

    Returns the bitwise AND result of x and y in binary complement.

    select bitwise_and(8, 7); -- 0
  • bitwise_not(x) → bigint

    Returns the result of x bitwise NOT in binary complement.

    select bitwise_not(8);-- -9
  • bitwise_or(x, y) → bigint

    Returns the bitwise OR result of x and y in binary complement.

    select bitwise_or(8,7);-- 15
  • bitwise_xor(x, y) → bigint

    Returns the bitwise XOR result of x and y in binary complementary code format.

    SELECT bitwise_xor(19,25); -- 10
  • bitwise_left_shift(value, shift) → [same as value]

    Description: Returns the value that is shifted leftwards by shift bits.

    SELECT bitwise_left_shift(1, 2); -- 4
    SELECT bitwise_left_shift(5, 2); -- 20
    SELECT bitwise_left_shift(0, 1); -- 0
    SELECT bitwise_left_shift(20, 0); -- 20
  • bitwise_right_shift(value, shift) → [same as value]

    Description: Returns the value that is shifted rightwards by shift bits.

    SELECT bitwise_right_shift(8, 3); -- 1
    SELECT bitwise_right_shift(9, 1); -- 4
    SELECT bitwise_right_shift(20, 0); -- 20
    SELECT bitwise_right_shift(0, 1); -- 0
    -- If the value is shifted rightwards by more than 64 bits, return 0.
    SELECT bitwise_right_shift( 12, 64); -- 0
  • bitwise_right_shift_arithmetic(value, shift) → [same as value]

    Description: Returns the value that is arithmetically right shifted. When shift is less than 64 bits, the return value is the same as the value returned by bitwise_right_shift. When shift reaches or exceeds 64 bits, this function returns 0 if the value is a positive number, and returns -1 if the value is a negative number.

    SELECT bitwise_right_shift_arithmetic( 12, 64); --  0 
    SELECT bitwise_right_shift_arithmetic(-45, 64); -- -1