How to left align a 32 bit integer?

Viewed 543

I have a 32 bit integer variable in hexadecimal format say 0x9B13488 or 0x1407E8. Defaultly it is right aligned to 0x099B1348 or 0x001407E8. But I want it to be left aligned to 0x9B134880 or 0x1407E800. Can anyone help me with it?

1 Answers

What you're really asking for is if the high-order 4 bits are set. You can do this as follows:

uint32_t left_align(uint32_t value)
{
    if (value) {
        while ((value & 0xF0000000U) == 0) {
            value <<= 4;
        }
    }
    return value;
}

As long as the value is non-zero and the higher order 4 bits are 0, shift left by 4 until they are non-zero.

Related