简体   繁体   中英

Is it wrong to assign value by dereferencing pointer to byte array?

I have a code where I dereference byte array pointer and assign the value to a variable. This worked ok for int and bool, but failed to work for float and double types. So I think there is a general issue I face. I made a sample:

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <algorithm>

using namespace std;
typedef unsigned char Byte;

int main( )
{
    vector<Byte> v(10);
    float f1 = 14.6;
    copy_n((Byte*)&f1, sizeof(float), (Byte*)&v[4]);

    float f2 = v[4];
    float f3 = 0;
    copy_n((Byte*)&v[4], sizeof(float), (Byte*)&f3);
    cout << "f2: " << f2 << " f3: " << f3 << endl;

    return 0;
}

std::copy_n works as expected, so I have to use it instead of f2 = v[4]

output: f2: 154 f3: 14.6

What is wrong with f2 = v[4] construction?

with float f2 = v[4] what happens is this: float f2 = (float) v[4] where v[4] is a Byte aka unsigned char. You take that element (just that element) and convert it to float.

In v[4] you have the least significant byte of f1,
...
In v[7] you have the most significant byte of f1

They are reversed because your system is little-endian.

With int it worked because you used a value smaller than 128 and because the system is little-endian. That is v[4] holds the least significant byte of the original f1 . As with float you ignore the other 3 bytes, but in this case (int smaller than 128) the rest of the bytes are 0 so you don't see any harm.

When doing

copy_n((Byte*)&v[4], sizeof(float), (Byte*)&f3);

you copied all the four bytes that constituted the float f1 from the byte buffer back to the float, while when you did

float f2 = v[4];

you only assign the least significant byte of the original float f1 whose value will be implicitly converted into a float and assigned to f2 .

Is it wrong to assign value by dereferencing pointer to byte array?

It isn't generally, but here it makes little sense since you are trying to extract the float back from the buffer.

f2 is a float , v[4] is an unsigned char .

Thus, you can assign from v[4] to f2 , but that entails a conversion which is value-preserving .

As you actually want to extract the bytes of a float from v , starting at index 4, that's obviously wrong.

With bool and int you lucked out, as your implementation is little-endian and the value you wanted to copy is smaller than SCHAR_MAX .

Your copy_n -construct works, as you can always copy any trivially copyable object (like builtin types) from/to a byte-array one unsigned char at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM