avva: (Default)
[personal profile] avva
Забавный комментарий в одном из файлов исходников пакета Judy:


// Test if Word has any of the 4 bytes == '\0':
//
// This arcane code takes advantage of the CPU having a fast barrel shifter and
// a carry bit. Doug stole this code from elsewhere, and we know it works, but
// we really can't explain why.

#define NOZEROBYTE(Word) \
((((((Word) - 0x01010101) | (Word)) ^ (Word)) & 0x80808080) ? 0 : 1)

Кто возьмётся объяснить? ;) У меня глаза слипаются и думать совершенно нет сил, я отправляюсь спать.

Update: Всё-таки подумал. Просто на самом деле. Но красиво.

Date: 2003-06-02 06:13 pm (UTC)
From: [identity profile] ex-ilyavinar899.livejournal.com
y = (((x-0x01010101) | x) ^ x) & 0x80808080

Consider one of the bytes of x. If it is not zero, then at least one of its bits is one; let's say that bit j is the least significant one. When we subtract 0x01 from it, bits 0..j-1 will be set to one, and bit j will be set to zero. When we OR it with x, bits 0..j will be set to one. When we XOR it with x, bits j..7 will be set to zero, and 0..j-1 will be set to one. So if the word contains no zero bytes, the result will not have any byte where bit 7 is set to one.

If the word contains a zero byte, then for the highest byte when we subtract 0x01 from it, it will be 0xFF. When we OR it with x, it will be 0xFF. When we XOR it with x, it will still be 0xFF. Its bit 7 will be set.

January 2026

S M T W T F S
    1 2 3
4 5 6 7 8 910
11121314151617
18192021222324
25262728293031

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jan. 9th, 2026 06:57 am
Powered by Dreamwidth Studios