krunalb wrote:
>
Hi,
I am trying to shift unsigned long long value by 64 bits and this is
what i get
#include <stdio.h>
int main()
{
unsigned short shiftby= 64;
fprintf(stderr, "Value (using hardcoded 64) : %llx\n", \
(((unsigned long long) ~0ULL) << 64));
fprintf(stderr, "Value (w/o hardcoded 64) : %llx\n", \
(((unsigned long long) ~0ULL) << shiftby));
}
gcc file.c
t2.c: In function `main':
t2.c:7: warning: left shift count >= width of type
<IMPORTANT>
Value (using hardcoded 64) : 0
Value (w/o hardcoded 64) : ffffffffffffffff
</IMPORTANT>
Why is the behavior different if we try to shift value by 64 bits using
a variable as against direct numeric "64"?
As mentioned elsewhere, this is UB. However, this may explain the
symptoms of UB that you are seeing on your particular platform. This
is, of course, pure conjecture based on the observed results.
1 - The compiler sees the hard-coded 64 bit shift and, knowing that
the value is only 64 bits to begin with, knows the result would
be zero, and compiles with a constant zero as the parameter.
(Or, perhaps, actually did the caluclation, as both values are
constants. In which case, it came up with the "expected" value
of zero.)
Note, too, the compiler warning for this line.
2 - When shifting by "shiftby" instead, it needs to compile code to
shift at the machine-code level, and places "64" in a register,
and executes an "unsigned left shift" of that amount. The CPU,
knowing that the operation is working on 64-bit values, only
uses the lower 6 bits of the shift amount. In this case, that
value is zero.
I ran into (2) recently on code which worked just fine on a platform
which supported 64-bit ints, but failed on a system which only supported
32-bit ints. In my case, I was splitting a value into two 32-bit values
to pass as parameters to a function. I did this by right-shifting the
value by 32 bits to get the high-order 32 bits. On the 64-bit-aware
platform, this worked just fine. On the 32-bit-only platform, the
shift of 32 bits was, at the CPU level, treated as a zero-bit shift
(the low-order 5 bits of the shift value being zero), causing the wrong
value for the "high 32 bits" parameter to be passed. (It should, of
course, been zero, as there were only the low-order 32 bits in the
value to begin with. Instead, it duplicated the low-order bits as
the high-order bits.)
--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody |
www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net |
www.fptech.com | <std_disclaimer.h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>