Simplify binary and and xor in C

Viewed 103

Is there a way so simplify the following expression in C?

result = (constant & value) ^ value;

The use case being:

#define ALL_SENSORS = (BIT(0) + BIT(1) + BIT(2) + BIT(19))  # = 524295

static int get_invalid_sensors(int sensor_mask) {
    return (ALL_SENSORS & sensor_mask) ^ sensor_mask;
}

Is it possible so simplify the binary operations into one, so I do not need to invoke sensor_mask two times?

3 Answers

How about (~ALL_SENSORS & sensor_mask)?

Well if you put this (or atleast similar) code into here. Then you can see the optimized code for example for RISC-V is

get_invalid_sensors: # @get_invalid_sensors
  not a0, a0
  and a0, a0, a1
  ret

From this you can realize that (~ALL_SENSORS & sensor_mask) is sufficient as already said. But you can also realize that the compiler will most likely be able to optimize your code anyway.

The goal of the expression (ALL_SENSORS & sensor_mask) ^ sensor_mask is to mask all bits in sensor_mask that are not in ALL_SENSORS. You can do this by ~ALL_SENSORS & sensor_mask, too.

Related