AWS Redshift已有按位&、<<、>>操作,如何实现OR和NOT标量操作?
Great question! While AWS Redshift doesn't expose dedicated operators for bitwise OR (|) and bitwise NOT (~) directly, you can easily implement both using the existing bitwise operators and basic arithmetic operations. Here's how:
|) You can calculate the bitwise OR of two integers using this bitwise arithmetic identity:
a | b = a + b - (a & b)
This works because when you add a and b, any bits set in both numbers get counted twice. Subtracting the bitwise AND (which isolates those overlapping 1s) corrects this, leaving you with the exact result of a bitwise OR.
Example
To compute 5 | 3 (binary 101 | 011 = 111, which equals 7):
SELECT 5 + 3 - (5 & 3); -- Returns 7
Custom Function (for reusability)
Wrap this logic into a function to simplify repeated use across queries:
CREATE OR REPLACE FUNCTION bitwise_or(a INT, b INT) RETURNS INT AS $$ SELECT a + b - (a & b); $$ LANGUAGE sql; -- Usage SELECT bitwise_or(5, 3); -- Returns 7
~) Bitwise NOT flips all bits of a number. The implementation varies slightly based on whether you're working with signed or unsigned integers:
For Signed Integers (Redshift's default INT type)
Use this identity based on two's complement arithmetic:
~x = -x - 1
Example
Flipping bits of 5 (binary 000...0101 → 111...1010, which is -6 in two's complement):
SELECT -5 - 1; -- Returns -6
For Unsigned Integers (e.g., 32-bit values)
Subtract the number from the maximum value for your target bit width. For 32-bit unsigned integers, that's 2^32 - 1 = 4294967295:
SELECT 4294967295 - 5; -- Returns 4294967290
Custom Functions
-- Signed bitwise NOT CREATE OR REPLACE FUNCTION bitwise_not(x INT) RETURNS INT AS $$ SELECT -x - 1; $$ LANGUAGE sql; -- Unsigned 32-bit bitwise NOT CREATE OR REPLACE FUNCTION bitwise_not_unsigned_32(x INT) RETURNS BIGINT AS $$ SELECT 4294967295 - x; $$ LANGUAGE sql; -- Usage SELECT bitwise_not(5); -- Returns -6 SELECT bitwise_not_unsigned_32(5); -- Returns 4294967290
内容的提问来源于stack exchange,提问作者JairoV

