Finding NULL byte in a long

Peter Klausler pmk at craycos.com
Fri Dec 14 02:35:52 AEST 1990


In article <198 at nazgul.UUCP> bright at nazgul.UUCP (Walter Bright) writes:
>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.
>
>Hmmm, how about:
>	p = memchr(&x,0,sizeof(x));

Performance, however, is sometimes important.

If one can be unportable and depend on two's-complement integer arithmetic,
eight-bit bytes, and the size of a long being, say, 64, give this a try:

	#define UPPERS	   0x8080808080808080
	#define ONES	   0x0101010101010101
	#define	HASNULL(x) (~((((x) | UPPERS) - ONES) | (x)) & UPPERS)

The solution for a 32-bit microcomputer is similar.

Finding the *position* of the null byte is a little trickier. It helps a lot
if your machine has a "leading zero count"/"find first set bit" instruction
and your compiler lets you use it.



More information about the Comp.lang.c mailing list