0

I have this code:

std::string GetBinary32( double value )
{
union
{
     float input;   // assumes sizeof(float) == sizeof(int)
     int   output;
}    data;

data.input = value;

std::bitset<sizeof(float) * CHAR_BIT>   bits(data.output);

std::string mystring = bits.to_string<char, std::char_traits<char>, std::allocator<char> >();

return mystring;
}

I want to get a 64 representation of the double.

what do i need to change?

Philipp
  • 4,645
  • 3
  • 47
  • 80
yardening2
  • 61
  • 4
  • Rather than guessing with `int`, use `uint32_t`. Then union `double` with `uint64_t` to get the 64 bit version. On the whole, this is not a good idea. It wanders into undefined behaviour as you're simultaneously using different members of a union. C++ give no guarantees that this is going to work as expected or the same on all implementations. It would be safer to discard the union and `memcpy` `input` to `output`. – user4581301 Nov 18 '15 at 20:19

1 Answers1

0

First of all, although the union method is a popular one to do this, bear in mind that accessing a union member different from the last written member is undefined behavior in C++. So you better test the result on your compiler and forget about protability.

That being said, assuming that your compiler uses the IEE754 (this can be checked as mentionned here ), you will need to change your union to contain a double and a long long. The long long will be on both 32bits and 64bits machines represented on 64bits as a de facto standard on windows and Unix (although the C++ standard doesn't enforce anything on the size but only on the ranges and the ordering of size between char, int, long etc...).

And of course adapt the bits variable with sizeof(double).

Community
  • 1
  • 1
Axel13fr
  • 11
  • 3