Tomáš Zato
Tomáš Zato

Reputation: 53119

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.

Upvotes: 3

Views: 2966

Answers (3)

Drew Dormann
Drew Dormann

Reputation: 63704

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";

Upvotes: 8

poitroae
poitroae

Reputation: 21357

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));

Upvotes: 3

user123
user123

Reputation: 9071

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.

Upvotes: 1

Related Questions