I'm making some code for a 16 bits microprocessor. My memory is quite limited at 128 KB. IAR C/C++ Compiler for MSP430 I need to implement some code to save some memory.
I tried to implemented this with this C characteristic implementation.
struct {
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status;
But with this bit of code I still only use 1 bit of a 16 bit word.
My goal is to use the same word sized bit of memory for two 8 bit variables. The first variable should be 8 bits left of the second variable.
struct {
unsigned int widthValidated : 8; //8 bits for this
unsigned int heightValidated : 8; // 8 left over for this
} status;
Is this possible? Are there any implementations of this or is there a library in C for this? How should I go about doing this?
You shouldn't use bit-fields for any purpose, particularly not for memory mapping, since they are very poorly standardized.
What you should do is to use the
stdint.h
types. Declare twouint8_t
variables. You save memory in microcontrollers by carefully picking the necessary type whenever declaring a variable.For example, in professional programs for limited microcontrollers, a typical for loop is written as
for(uint8_t i=0; ...
and not with "sloppy typing"for(int i=0; ...
.The trick is: whenever you declare any variable, then always consider what is the maximum value that variable might get. By doing so, you save memory and prevent overflow bugs.