Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!uakari.primate.wisc.edu!pikes!aspen.craycos.com!pmk From: pmk@craycos.com (Peter Klausler) Newsgroups: comp.lang.c Subject: Re: Finding NULL byte in a long Message-ID: <1990Dec13.153552.1862@craycos.com> Date: 13 Dec 90 15:35:52 GMT References: <1990Dec5.033206.10463@nimbus3.uucp> <198@nazgul.UUCP> Organization: Cray Computer Corporation Lines: 25 In article <198@nazgul.UUCP> bright@nazgul.UUCP (Walter Bright) writes: >In article <1990Dec5.033206.10463@nimbus3.uucp> djs@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.