Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REPEAT_BYTE(x) macro

I was looking the code in kernel.h header file in /usr/src/linux-headers-3.11-.../include/linux/, I stumbled upon this macro (line 47) :

#define REPEAT_BYTE(x)  ((~0ul / 0xff) * (x))

After running this example I made:

#include <stdio.h>

#define REPEAT_BYTE(x) ((~0ul / 0xff) * (x))

int main(void)
{
        long z = 12;    
        fprintf(stderr, "\tz = %ldd (0x%lX)\n"
                        "\tREPEAT_BYTE(%ldd) = %ldd (0x%lX)\n",
                        z, z, z, REPEAT_BYTE(z), REPEAT_BYTE(z));
        return 0;
}

I've figured out what it does: It receives an int between 0 and 255(including them), so any one-byte long int, and it repeats that byte. This is obvious (except macro's name) when looking at the output:

z = 12d (0xC)
REPEAT_BYTE(12d) = 868082074056920076d (0xC0C0C0C0C0C0C0C)

However, I still can't understand how does this expression work: ((~0ul / 0xff) * (x)), I could use some help with it.

Thanks a lot in advance!

like image 825
chrk Avatar asked Jan 10 '23 13:01

chrk


1 Answers

On a 64-bit machine, ~0ul is 0xffffffffffffffff. Divide that by 0xff and you get 0x0101010101010101. Multiply by an 8-bit value and you get that 8-bit value repeated 8 times.

like image 143
user3386109 Avatar answered Jan 17 '23 14:01

user3386109