Hacker News new | ask | show | jobs
by rcoveson 2338 days ago
You could subtract the value of '\n' from each byte, bitwise-or the result with its negated value, right shift the sign bit into the least significant position, and push that into an accumulator.

Basically, it is possible to reduce a byte into a one or a zero if it does or does not match a value using only bitwise instructions. I don't know if the way I just described uses the fewest instructions, but you can definitely do it without branching.

In fact, you can do this to test any integer comparison. Start by subtracting the arguments to the comparison operator, and then use one of these "squash" functions for the comparison operator in question (assuming 32 bit signed integers are being compared):

== : ~(c | -c) >>> 31

!= : (c | -c) >>> 31

> : -c >>> 31

>= : ~c >>> 31

< : c >>> 31

<= : ~-c >>> 31