Harm Prins Harm Prins - 1 month ago 11
C Question

C: Most efficient way to store variables where every bit matters

To start off: this might be a duplicate, but i can't seem to find a definitive answer on this question after having searched for it on google.

For a project i am designing a script that makes 2 ATMega328p chips communicate. At this moment i'm testing the best speed to do this, but my goal is to achieve really high baudrates. I have plenty of experience with making code efficient, but not with the memory management part. The problem:

I want to store a multiple of 8 bits (ex.: 48 bits). My first thought was to use an array of length 6 and type

uint8_t
, but I don't know how efficient arrays are compared to other types. Some people say pointers are more efficient and others say it doesn't matter, but I cant find a definitive answer on what the case is for really small amounts of memory. last quesion: I know the size of the sent bits will never be bigger than 64 bits, so would it matter if i just Always jused uint64_t?

Edit:
to clarify: My goal is to minimize the storage size, not the transmission size

Edit2:
What i meant by having a varying size: The size is determined on compile time, not while running the program.

Answer

The ATmega328p is a 8bit processor. All of its instructions are 8bit. Nothing will be faster than simply having an uint8_t array.

What you can do is, when you compile, look at your .lss file, it will show you the assmebly code, then you can look up the AVR instruction set and see the clock cycles each one will take. I think you will find using a uint64_t will just add unncessary overhead unless you are very careful with the way you are putting the bytes into it.