The left shift is shifting 1, which is int
by default and probably 32 bits on your machine. When you shift 1<<32
, the result is undefined, which means it is not predictable anymore, as it could be anything.
On some processors, 1<<32
might result in shifting the bit off the high end of the integer and resulting in 0. On other processors, the 32 shift is modulo the register size, so effective it is a zero shift, and the result is 1. In any case, it is undefined.
(See What's bad about shifting a 32-bit variable 32 bits? for a discussion on this).
Note also that sizeof
returns units char
or "bytes" (these are defined to be the same in C, sizeof(char) == 1
always), but C does not guarantee that a byte is 8 bits. There is standard macro CHAR_BIT
to get the bit size of a char
.
Try this
#include <limits.h>
template<class T>
T bottom_half() {
T halfway = ((sizeof(T) * CHAR_BIT) / 2);
T mask = ((T)1 << halfway) - 1;
return mask;
}