How to interpret binary data as an integer?

The code base on the desktop contains some code that looks something like this:

#define DATA_LENGTH 64

u_int32 SmartKey::SerialNumber()
{
    unsigned char data[DATA_LENGTH];
    // ... initialized data buffer
    return *(u_int32*)data;
}

This code works correctly, but GCC gives the following warning:

warning: dereferencing pointer ‘serialNumber’ does break strict-aliasing rules

Can someone explain this warning? Is this code potentially dangerous? How can this be improved?

Update
Thanks to the answer of James McNellis, I came up with the following useful function:

template<class T, class Data>
T BinaryCast(const Data & inData)
{
    T ret;
    std::copy(&inData[0], &inData[0] + sizeof(ret), reinterpret_cast<char*>(&ret));
    return ret;
}

u_int32 SmartKey::SerialNumber()
{
    unsigned char data[DATA_LENGTH];
    // ... initialized data buffer
    return BinaryCast<u_int32>(data);
}

Feel free to suggest improvements!

+5
source share
4 answers

The warning is because you are violating the strict pseudonir rule .

- data u_int32 :

unsigned char data[DATA_LENGTH];
// ... initialized data buffer

u_int32 i;
assert(sizeof (i) <= DATA_LENGTH);
std::copy(&data[0], &data[0] + sizeof (i), reinterpret_cast<char*>(&i));
return i;

, ++ char.

(std::copy() <algorithm>)

+11

C ++ , , - undefined. , . , , , .

C/++ char, , char, reinterpret - . , .

, char u_int32.

, , - u_int32, memcpy

u_int32 SmartKey::SerialNumber()
{
    unsigned char data[DATA_LENGTH];
    u_int32 u;
    // ...
    memcpy(&u, data, sizeof u);
    return u;
}

, , u_int32 .

+2

I think the problem is that somewhere in your emulated code the data structure [] is initialized. I don’t think this has anything to do with your cast, and that’s normal.

0
source

Not sure, but I think you can do this:

return (u_int32)&data;
-1
source

All Articles