user3313574
user3313574

Reputation:

Convert double to 8 length char array in c++

I want to convert a double to a 8 length char array in c++. The problem is that I want to cover all the number of bytes of the double type (double is not always 8 byte long in c++).

The char array is just used to store the bytes of the double, as if char type = byte type.

Any ideas?

Upvotes: 0

Views: 478

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476930

Yes, you can always treat any object as an array of bytes. To access the bytes, use a reinterpret-cast:

T x;    // any object

unsigned char const * bytes = reinterpret_cast<unsigned char const *>)(&x);

for (std::size_t i = 0; i != sizeof(T); ++i)
{
    std::fprintf("Byte %zu is %02X\n", bytes[i]);   // assuming CHAR_BIT == 8
}

Note that there isn't generally a way to know which of the bytes are part of the object representation and what their actual meaning is. For example, a long double may on certain platforms have size 12 or 16 but only have 10 relevant bytes, and you don't know which one is which. Though for a double with size 8 it's reasonable to assume that there's no padding and that the bytes make up an IEEE-754 representation in linear order. Your platform manual might tell you.

Upvotes: 1

Related Questions