The first part is self-explanatory: the upper 16 bits are removed with & 0xffff
masking.
Subtracting (x & 0x8000) << 1
is a trick that keeps the proper sign of the 16-bit number in the 32-bit result: for example, 0xffff
, a -1 in 16-bit representation, gets converted to 0xffffffff
, which is also -1 in 32-bit representation. This is better than using a conditional, because it is branch-free.
Another trick that you could use is
(((x & 0xFFFF) << 16) >> 16)
This lets the sign bit of 16-bit number "touch" the sign bit of 32-bit number, letting the right shift to sign-extend the result.
Note: If you are looking for a binary String
representation of the number, only x & 0xffff
masking is necessary, because the upper 16 bits are dropped from the string result anyway. This Q&A explains how to obtain a binary representation of an integer with the appropriate number of leading zeros.