Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocate the memory of struct more efficiently in C++

Tags:

c++

struct

I'm trying the construct a struct in C++ as below:

struct kmer_value {
    uint32_t count : 32;
    uint32_t  path_length : 32;
    uint8_t acgt_prev : 4;
    uint8_t  acgt_next : 4;
}

The struct currently takes the memory of 12 bytes, but I want to reduce the size to 9 bytes. Is there any way to realize it?

Thank you.

like image 643
Scarlett Huo Avatar asked Jan 03 '23 19:01

Scarlett Huo


1 Answers

There's no portable solution. For GCC that would be

struct __attribute__((packed)) kmer_value {
  uint32_t count : 32;
  uint32_t path_length : 32;
  uint8_t acgt_prev : 4;
  uint8_t acgt_next : 4;
};

In MSVC #pragma pack can achieve the same effect.

Consult your compiler's documentation.

like image 66
AnT Avatar answered Jan 18 '23 21:01

AnT