c - Copying a 32 bit integer to a 64 bit integer is undefined? -
well, know << 32
undefined on 32-bit integers... know pointer casts , dereferences don't mix much.
but 1 kind of none of them.
test.c:
#include <stdio.h> #include <stdlib.h> #define __stdc_format_macros #include <inttypes.h> int main(void) { uint64_t tmp = 1 << 31; printf("%" prix64 "\n", tmp); return 0; }
then this:
$ gcc test.c -o test $ ./test ffffffff80000000
why did corrupt first 4 bytes?
lower shifts work fine. if printf("%x\n", 1 << 31)
, yields 80000000 expected. if tmp 32 bits, works fine.
u64
, __u64
have quirk.
you didn't corrupt anything, didn't shift 64-bit number. in c, single 1
defaults int
. if want use 1
unsigned long
(or unsigned
), tell compiler suffixing number (ul
or u
-- (ull
on x86)), otherwise shifting signed number:
uint64_t tmp = 1ull << 31;
output
80000000