tags:

views:

43

answers:

2

At work we have the following construct to enable interpreting an IP address as either an array of 4 bytes, or as a 32-bit integer:

static const unsigned int IP_V4_LENGTH = 4;
union IPv4Data
{
    u_int32 address;
    u_int8 bytes[IP_V4_LENGTH];
};

This works fine, but I'm a little worried after reading chapter 97 "Don't use unions to reinterpret representation" of the book C++ coding standards. The example in the book is more insidious though and I'm not sure if it applies to my code.

Are there any potential issues with my code?

Update
The class around it is designed to have the byte array start with the most significant byte. Thus the constructor taking a u_int32 has to reverse it:

Ipv4Address::Ipv4Address(u_int32 inAddress) {
    // For little endian, we have to revert the bytes. For big endian, we don't
    mData.address = htonl(inAddress);
}

Ipv4Address::operator u_int32() const {
    return ntohl(mData.address);
}
A: 

No problem, as the represantation is the same you just access ist differently.

Code Clown
+2  A: 

According to the standard, reading a member of a union other than the last one written is undefined behavior. Unions were designed to save space, no for data type conversion. That said, what you are doing will probably work on all mainstream platforms and compilers.

KeithB
"reading a member of a union other than the last one written is undefined behavior." Yikes, that's a severe restriction!
StackedCrooked