Figuring out what exactly this bitwise AND and LSL does in C

1.  long int temp;
2.  int product = -1;

3.  temp = (long int)product & 0xFFFFFFFF;

4.  temp = temp << 32;

I know that temp is 64-bit while product is 32-bit.

I am slightly confused about lines 3 and 4.

We are casting product as a long int, which means product should get represented as 64-bit and doing a bitwise AND with 0xFFFFFFFF. The hexadecimal representation of 0xFFFFFFFF is all 1's, so the AND should preserve the binary representation of -1?

Since -1 in binary is 1111111111111111, would temp now be 32 1's followed by 32 0's, or vice versa? If the former, is there any point to doing the left shift on line 4?

I am mainly confused about the conversion of 32-bit to 64-bit here and how it looks in binary.

asked on Stack Overflow Oct 10, 2019 by qbuffer

1 Answer


On line 3, the following happens:

Since the type cast operator has higher operator precedence than the & operator, the program first converts the 32-bit respresentation of the number -1 in the variable product to a temporary 64-bit representation of the number -1. It does this by sign extending the upper 32 bits. Since the sign bit has the number 1, the upper 32 bits will be filled with 1s, so that the temporary 64-bit value now consists of 64 1s. Now, that temporary value is ANDed with 0xFFFFFFFF, which keeps the lower 32 bits intact and zeroes the upper 32 bits. So, now the temporary value has the value 0x00000000FFFFFFFF, which no longer corresponds to -1, because the value is now positive, since the sign bit (the highest bit) is now set to zero. This temporary value has the value 4,294,967,295 in decimal. It is now assigned to the variable temp.

On line 4, the following happens:

The value in the variable temp, which is 0x00000000FFFFFFFF, is now left shifted by 32 bits, to the value 0xFFFFFFFF00000000. This new value is now assigned to temp. Since the sign bit (the highest bit) is now set to 1 again, the value is negative, but it is no longer -1. Its value now is -4,294,967,296 in decimal representation. See this Wikipedia article for more information on how negative numbers are represented in binary.

answered on Stack Overflow Oct 10, 2019 by Andreas Wenzel • edited Oct 19, 2019 by Andreas Wenzel

User contributions licensed under CC BY-SA 3.0