I wonder why the code below prints "wrong".
double x = 0x8000000000000000;
signed long long v1 = (signed long long)(x);
signed long long v2 = *(signed long long *)(&x);
printf( v1 == v2? "correct\n" : "wrong\n" );
I tried to print out binary representation of v1 and v2 respectively by code below:
printf( "v1 = 0b" );
for ( int i = 63; i > 0; i-- ) {
printf( "%d", ( ( v1 >> i ) & 1 ) );
}
printf( "\n" );
printf( "v2 = 0b" );
for ( int i = 63; i > 0; i-- ) {
printf( "%d", ( ( v2 >> i ) & 1 ) );
}
printf( "\n" );
It turns out v1 is correct, but v2 is 0b010000111110000000000000000000000000000000000000000000000000000
.
Could anyone be so kind to teach what happens here?
Also, I was wondering if C standard offers any way of printing out underlying representation of binary or hex, such that my print scheme can be replaced by an one-line function call?
x
is?(signed long long)
you shouldn't do this at all in C++. And thisdouble x = 0x8000000000000000;
is also not going to do what you think it does. (It will not initialize using a bit-pattern but maps an integer number on the "closest" representable floating point number