Pregunta

I'm looking for a branchless bitwise operation that can determine with a given mask :

Mask : 0xFF0000 Value : 0xAA0000 return : true

Mask : 0xFF0000 Value : 0xAA00AA return : false

Mask : 0xFF00FF Value : 0xBB00AA return : true

Mask : 0xFF00FF Value : 0x0000AA return : false

Mask : 0xFF00FF Value : 0xAA0000 return : false

Mask : 0xFF00FF Value : 0x0A00AA return : true

That's is : it must returns true if :

  • the mask has a byte set to 0, the value must have the same byte to 0.
  • the mask has a byte set to > 0, the value must have the same byte different of 0.

Edit :

0xFFFF00 and 0x00AA00 should not match. If the mask has a byte > 0, the value must have the same byte > 0.

That's is : If the mask has this pattern [XX][00][XX], the value must have the same. Where XX can be from 01 to FF in the value.

Thanks!

¿Fue útil?

Solución

I'm assuming that we're only dealing with the low-order three bytes, as per the question.

A simple solution (17 operations):

((mask & 0x0000FF) == 0) == ((value & 0x0000FF) == 0) &&
((mask & 0x00FF00) == 0) == ((value & 0x00FF00) == 0) &&
((mask & 0xFF0000) == 0) == ((value & 0xFF0000) == 0)

A better solution (9 operations):

(((mask & 0x7F7F7F) + 0x7F7F7F | mask) & 0x808080) ==
(((value & 0x7F7F7F) + 0x7F7F7F | value) & 0x808080)

A third solution (9 operations):

!((((mask & 0x7F7F7F) + 0x7F7F7F | mask) ^
((value & 0x7F7F7F) + 0x7F7F7F | value)) & 0x808080)

The third solution can be reduced to 8 operations by dropping the ! surrounding the entire expression if your code is prepared to handle zero as pass and non-zero as fail.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top