C++ Only Store Specific Bytes of a double in a char*

Viewed 87

Off the bat I am unfortunately using an older version of c++ (I believe 98) so c++11 goodies are unavailable to me.

That aside, I was wondering- is it possible to only store specific bytes of a double in a char* buffer? For example, if I have a double that has a low value and therefore only uses 3 bytes of data can I then copy just 3 bytes of data into a char* buffer?

I know it is possible to copy full doubles into a char* buffer. Currently I am doing so and printing out the binary of the char* buffer afterwards using this code:

char* buffer = new char[8]; // A double is 8 bytes
memset(buffer, 0, sizeof(buffer)); // Fill the buffer with 0's

double value = 243;
memcpy(&buffer[0], &value, 8); // copy all 8 bytes (sizeof(value) is better here, I'm just typing '8' for readability)

for (int i = sizeof(value); i > 0; i --)
{
  std::bitset<8> x(buffer[i-1]); // 8 bits per byte
  std::cout << x << " ";
}

The output of the above code is as expected:

01000000 01101110 01100000 00000000 00000000 00000000 00000000 00000000

If I try and only copy the first 3 bytes into the char* buffer, however, it appears that I don't end up copying over anything at all. Here is the code I'm attempting to use:

char* buffer = new char[8]; // A double is 8 bytes
memset(buffer, 0, sizeof(buffer)); // Fill the buffer with 0's

double value = 243;
memcpy(&buffer[0], &value, 3); // Only copy over 3 bytes

for (int i = sizeof(value); i > 0; i --)
{
  std::bitset<8> x(buffer[i-1]); // 8 bits per byte
  std::cout << x << " ";
}

The output of the above code is an empty buffer:

00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000

Is there a way for me to only copy 3 bytes of this double over to a char* buffer that I am missing?

Thanks!

1 Answers

You are copying over the wrong bytes, you're computer is in little endian and so the 3 bytes you want to copy over will actually be the last three bytes of the double. If you change the copy line of your code to this

memcpy(&buffer[0], (void*)(&value)+5, 3); // Copy the last three bytes

you get a correct result of

00000000 00000000 00000000 00000000 00000000 01000000 01101110 01100000

Related