Search code examples
cbit-manipulationverilogbitwise-operatorsbitwise-and

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?


Solution

  • 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;
      }