A simple broadcast will do:
double d = 0.5; const unsigned char * buf = reinterpret_cast<const unsigned char *>(&d); for (unsigned int i = 0; i != sizeof(double); ++i) std::printf("The byte at position %u is 0x%02X.\n", i, buf[i]);
Where sign and exponent bits depend on your platform and content ability. If your floats are IEE754, if the sign and exponent are in front, and if CHAR_BIT == 8
, you can try the following:
const bool sign = buf[0] & 0x80; const int exponent = ((buf[0] & 0x7F) << 4) + (buf[1] >> 4) - 1023;
(In C, let's say (const unsigned char *)(&d)
for translation.)
Update. To create an integer with the same bits, you first need to make an integer, and then copy:
unsigned long long int u; unsigned char * pu = reinterpret_cast<unsigned char *>(&u); std::copy(buf, buf + sizeof(double), pu);
To do this, you need to keep in mind several things: the size of the integer must be sufficient (the static statement for sizeof(double) <= sizeof(unsigned long long int)
should do the trick), and if the integer is actually larger, then you are only copying to its parts. I'm sure you can figure it out though :-) (You can use the magic of templates to create an integer of the right size if you really wanted to.)
source share