johnny-john
johnny-john

Reputation: 854

C++: Data alignment and efficient use of memory (in both time and space)

Cheers every!

I want to store some data in memory in a structure, or in an array. My problem is data alignment. I cant really use a 8 byte data next to a char since they will take up 16 bytes together.

Now I would live happy with a single 8 byte field, like a char and using the remaining 7 bytes to store other data.

How do I do that? What are the performance penalties to pay? Thanks people.

Upvotes: 1

Views: 259

Answers (2)

Ben Jackson
Ben Jackson

Reputation: 93700

You can automate the bit shifting math suggested by Arkku with bitfields:

struct {
    uint64_t  one_byte:8;
    uint64_t  seven_byte:56;
};

There will be slight access overhead but it's worth it if you plan to use so many of these that space is at a premium. Over so much memory the improved cache locality will easily offset a few shift/mask operations.

Upvotes: 4

Arkku
Arkku

Reputation: 42119

With your 8-byte field, you can get the lowest 8 bits with field & 0xFF and the rest with field >> 8. To assign values you can similarly construct the field with (seven << 8) | (one & 0xFF) (you can omit the 0xFF here if you know one is only 8 bits).

The penalty is having to do these operations every time you use the data.

(As more of a hack, you may be able to access the one-byte part directly with casts, but then byte order within the 8-byte word will start to matter.)

Upvotes: 2

Related Questions