AZ123
AZ123

Reputation: 184

Bitwise Reduction Operators in C

Are there unary bitwise reduction operators in C like there are in Verilog?

Like in Verilog we have:

$display (" &  4'b1001 = %b", (&  4'b1001));

and the output of the function above is:

  &  4'b1001 = 0

I couldn't find a similar operator for C. Is there such an operation in C language?

Upvotes: 1

Views: 547

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 222274

In C, assuming unsigned or two’s complement, !~x or ~x == 0 serves as a bitwise AND; it is 1 if and only if each bit of x is 1.

!!x or x != 0 serves as a bitwise OR; it is 1 if any bit of x is 1.

The negations, not properly called NAND or NOR since they do not apply a NAND or NOR in a bitwise fashion but rather apply a NOT to the bitwise AND or OR, are simply !!~x or ~x != 0 and !x or x == 0.

There is no bitwise XOR in the operations specified by the C standard. GCC has __builtin_parity which can provide this.

The above apply to the full width of x. Narrower widths can be implemented by setting the extra bits to identity elements (1 for AND, 0 for OR and XOR).

Upvotes: 4

G. Sliepen
G. Sliepen

Reputation: 7973

There are no dedicated operators for this, however in most cases you can achieve the same result using bitwise operators and casting the result to a bool, which effectively is a single bit. For example:

  • AND: bitwise invert, convert to bool, negate:
    bool and_reduction_4_bits(int n) {
        return !(~n & 0b1111); // C23 adds binary literals
    }
    
  • OR: just convert to bool
    bool or_reduction(int n) {
        return n; // works for any number of bits
    }
    

The tricky one is XOR reduction. This could be done if you have a way to count the number of bits set, and then just check if that number is odd. Some compilers provide a builtin popcount() function to do that. If not, you can create your own function using bit twiddling hacks.

  • XOR: count bits, check if odd
    bool xor_reduction(int n) {
        return popcount(n) & 1;
    }
    

Upvotes: 1

Related Questions