HuangJie HuangJie - 29 days ago 7
C Question

Bit Twiddling Hacks

Can anyone help explain what does

val
stand for in the following example? I totally have no idea what is the value of
val
.

#define SPLAT(p) (*(p) * (~0UL / 255))

uint8_t *page;
unsigned long val = SPLAT(page);

Answer

Assume that a long is 32 bits. The ~0UL is a bit pattern of all ones i.e. 0xffffffff. Now divide by 255 or 0xff giving 0x01010101.

Multiply this with an 8 bit quantity and you will get the same byte 4 times; e.g 0x5a * 0x01010101 = 0x5a5a5a5a.