1

i'm currently programming in c for an 8-bit microcontroller from atmel (Atmega328). In the program, i've got an 8-bit array storing thousands of 2 bit integers and it is therefore located in the program memory space. Currently, I put four 2-bit integers in each byte, but now when I think of it more closely, it seems stupid...

Would it not be more efficient to use an array with 16-bit values and store eight 2-bit variables in each location?

The microcontroller (atmega328p) is an 8-bit IC with 16 bits for each machine instruction.

Hassenboy
  • 165
  • 1
  • 7
  • 1
    What do you mean by more efficient? – antonijn Feb 05 '13 at 18:36
  • compile then disassemble to see what the compiler is doing. It is likely packing the 8 bit values into memory such that you are not losing half your memory – old_timer Feb 05 '13 at 18:36
  • @dwelch: Yep, that's how it works. Either way you get four elements per byte of progmem. –  Feb 05 '13 at 18:37
  • 1
    That is how I would hope it works, I always like to KNOW the compiler is doing what I HOPE it is doing... – old_timer Feb 05 '13 at 18:41
  • @dwelch: I've worked with avr-gcc. That is exactly how it works. –  Feb 05 '13 at 18:54
  • The AVRs access FLASH/program memory based on single bytes. (Most?) machine instructions are 16 bits wide, yet the FLASH is still organized as a contiguous array of 8 bit values, each of which can be directly addressed without any alignment. – JimmyB Feb 12 '13 at 11:25

2 Answers2

1

How would it be more efficient?

Space efficiency

2-bit integers take up 2 bits. You can't do much more about it.

Time efficiency

No matter how you pack them, you'll still need to perform the same amount bitwise operations to extract your 2-bit numbers from the larger value.

salezica
  • 74,081
  • 25
  • 105
  • 166
  • 1
    Unless OP is clearing out the array or updating values of more than one 2-bit integer at a time. – Lee Meador Feb 05 '13 at 18:42
  • The array is in program memory, which is pretty much read-only on AVR. –  Feb 05 '13 at 18:52
  • I think the concern was taking up 16 bit locations with 8 bits of array and 8 bits discarded (4 2 bit items rather than 8 2 bit items). I dont think it is a concern. – old_timer Feb 05 '13 at 19:16
  • But he said "8 2-bit variables in each location"? – salezica Feb 05 '13 at 19:46
0

As this is an 8-bit processor with 8-bit registers it would not improve things to operate on 16-bit operands when programming in assembly language. But things are more complicated for c compilers. It is absolutely possible that the compiler converts 8-bit operands into 16-bit operands performing 16-bit arithmetic, as the int size will usually be at least 16 bits for almost any compiler I know.

So disassembling is really the way to go.