Finding NULL byte in a long

Paul N. Hilfinger hilfingr at rama.cs.cornell.edu
Wed Dec 12 08:01:51 AEST 1990


In article <1990Dec5.033206.10463 at nimbus3.uucp> djs at nimbus3.UUCP (Doug) writes:
>
>I know this has been on the net before, since I thought I saved it,
>but can't find it now.  Anyway, could someone tell me what the
>C expression is that tells you if a long has a NULL byte in it.
>This is without masking each byte and testing it for 0.  It is very
>clever and non-obvious.  Thanks.

Normally, I'd reply by e-mail, but I can't believe that the formulae below
are the best one can do, and I'd like to hear of better solutions
myself.

Assuming 32-bit, 2's complement longs, I believe the following
expressions both have the property of being non-zero iff the long
value x contains at least one 0 byte:

	(~x & 0x7f7f7f7f) + 0x01010101 & ~x & 0x80808080
	((x - 0x01010101) ^ x) & ~x & 0x80808080

Paul Hilfinger



More information about the Comp.lang.c mailing list