Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I spent about twenty minutes looking at this function trying to figure out what it does. It looks like it uses a neat trick to compare native integers instead of bytes for speed, but I just couldn't figure out what it does. Then I realised it's part of the standard library and "man memchr" told me what it does...


I mean, it's definitely a neat way to optimize comparisons for the CPU's word size. The problem is with completely unexplained things like:

  #define ONES ((size_t)-1/UCHAR_MAX)
Reading through the loop, it seems as though it will create, e.g., 0x01010101 for a 32-bit machine with 8-bit bytes. And sure enough, if you calculate ((2^32)-1)/255 that's exactly what you get. But I never would've known that without going through the code and proving to myself that the definitely of ONES actually makes sense.

If you write code like this and there are never any bugs then fine, I guess. But there will bugs.


The whole ONES... HASZERO shenanigans is somewhat explained here: https://graphics.stanford.edu/~seander/bithacks.html#ZeroInW... as well as the entry after it.

Edit: And most likely in the excellent book "Hacker's Delight" as well.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: