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:

    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.