integer promotion of bit-wise operation and endiannes issue

Mark Source

Consider the following snippet from code running in the Linux kernel:

    char *d;
    u32 mask, step, val;
    /* d is initialized with valid pointer pointing at buffer,
and mask, step and val are initialized to some sane values as well. */
    val = (*d & mask) >> step;

As you see only d is of char * type, the rest are unsigned integers. I know that C performs type conversions automatically when values of differing types participate in expressions, in this case bit-wise operation. So, I'm assuming it is guaranteed that *d will be promoted to uint32_t as well?

If this assumption is correct, my 2nd question would be about the byte-order of 4 bytes located at memory pointed by d. I think it has to be whatever byte-order the host implements, or if it's networking, then strictly big-endian.



answered 3 months ago dbush #1

Because d has type char * it reads a single byte at the address pointed to by d. So the expression *d has type char which has the value of the byte pointed to by d. Endianness doesn't matter here because only a single byte is read from d.

In the larger expression *d & mask, the value *d which has type char is converted to uint32_t for use in the expression.

comments powered by Disqus