简体   繁体   中英

Cast char* to double - as bytes

I have a byte array that represents double:

char number[8];

I need to cast this to actual double (which has 8 bytes as well). Based on advice I tried this, but it failed:

std::cout<<(*((*double)number))<<" is my number.\n";

Why did it fail and what should I do? I can, of course, extract the data using some << magic, but I don't want to do this - it would consume memory and make code too robust.

Why did it fail?

You have a typo here.

std::cout<<(*((*double)number))<<" is my number.\n";

It should be:

std::cout<<(*((double*)number))<<" is my number.\n";

and what should I do?

You could reduce the number of parenthesis used.

std::cout<< *(double*)number <<" is my number.\n";

You should use C++ casts instead of C casts, so it's clear what you're doing.

std::cout<< *reinterpret_cast<double*>(number) <<" is my number.\n";

If you use c++, then use reinterpret_cast . C++ have much more expressive, as you see.

// cool c++
double value = *reinterpret_cast<double*>(number);

// c style
double value = (*((double*)number));
char number[8];
double d;
// number is assumed to be filled with a buffer representing a double.
memcpy(&d, &number, sizeof(double));
std::cout << d;

Not sure if the sizeof is needed. The damage was already dealt when the assumption that a double is 8 bytes was made. I don't know what it says in the standard about doubles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM