Hi,
What will happen in following scenario..
long a = -2;
longlong b = a
long c;
c = *(ulonglong *)&b;
b = c;
also when
long d;
d = *&b;
b = d;
What will be the value of b ? When will it lose the upper 32bits ?
regards
amit
Let me know if I've misinterpreted anything you wrote up there:
#include <stdio.h>
int main()
{
long a = -2;
printf("a = %ld\n", a);
printf("a (unsigned) = %uld\n\n", a);
long long b = a;
printf("b = %lld\n", b);
printf("b (unsigned) = %llu\n\n", b);
long c;
c = *(unsigned long long *)&b;
printf("c (via pointers) = %ld\n", c);
printf("c (via pointers, unsigned) = %uld\n\n", c);
/* I've added this (why bother with the pointers? */
c = (unsigned long long) b;
printf("c (no pointers) = %ld\n", c);
printf("c (no pointers, unsigned) = %uld\n\n", c);
b = c;
long d;
d = *&b;
printf("d = %ld\n", d);
printf("d (unsigned) = %uld\n\n", d);
b = d;
printf("b (from d) = %lld\n", b);
printf("b (from d) (unsigned) = %llu\n\n", b);
b = (unsigned) d;
printf("b (from unsigned d) = %lld\n", b);
printf("b (from unsigned d) (unsigned) = %llu\n\n", b);
return 0;
}
Output:
a = -2
a (unsigned) = 4294967294ld
b = -2
b (unsigned) = 18446744073709551614
c (via pointers) = -2
c (via pointers, unsigned) = 4294967294ld
c (no pointers) = -2
c (no pointers, unsigned) = 4294967294ld
d = -2
d (unsigned) = 4294967294ld
b (from d) = -2
b (from d) (unsigned) = 18446744073709551614
b (from unsigned d) = 4294967294
b (from unsigned d) (unsigned) = 4294967294
So note that you do lose finally lose the upper 32 bits when assigning from
d to c, /if/ you first cast d's value to unsigned. So long as you're doing
the assignment as a signed value, you'll get sign extension.
(Compiled with Comeau 4.3.3, Dinkum Unabridged Library)
-leor