Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ What does casting do in the low level?

Somebody told me that type-casting C conversions does only change how the system interprets the information (for example, casting the char 'A' into int does return 65 when using cout to print it since in memory it stays as 01000001).

However, I noticed that, when casting floating point numbers into same width integers, the value is conserved and not changed, as it would be if only the interpretation was changed. For example, let X be a double precision floating point number:

double X = 3.14159;

As far as I now, when inspecting &X we will find (converted by decimal to binary converter):

01000000 00001001 00100001 11111001 11110000 00011011 10000110 01101110

But, as some of you would already know, when doing:

long long Y = (long long)X;

Y will be 3, the truncated version of X, instead of 4614256650576692846, the value it would get when looking at the binary values at &X if looking for a long long.

So, I think it is clear that they were wrong but, then, how does casting work in low level? Is there any detection of whether the value would be changed or not? How would you code it to get Y = 4614256650576692846 instead of Y = 3?

like image 517
Néstor Llop Avatar asked Nov 02 '25 03:11

Néstor Llop


1 Answers

Casting will try to preserve the values as precise as possible. You can use memcpy() to copy bit patterns.

#include <iostream>
#include <cstring>

int main() {
    double X = 3.14159;
    long long Y;
    memcpy(&Y, &X, sizeof(Y));
    std::cout << Y << '\n';
    return 0;
}
like image 147
MikeCAT Avatar answered Nov 03 '25 16:11

MikeCAT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!