Go Down

Topic: Boolean memory size (Read 736 times) previous topic - next topic

Steen

Hi

I was wondering if a boolean gets saved as one bit, or as a full byte. Since it makes a huge difference in memory usage, but I don't know if the arduino is able to address only on bit. So if you'd save 8 booleans, that would still only take up 1 byte instead of 8 bytes, or is this false?

Thanks

JosAH

A boolean takes up one byte in C++ (zero or not zero for false/true); you can use bit fields in C/C++ that take up single bits; eight of them (one bit each) take up a single byte again.

kind regards,

Jos

gutbag

Try something like:

Serial.print(sizeof(boolean));

This will print the number of *bytes* used for booleans.

Steen


A boolean takes up one byte in C++ (zero or not zero for false/true); you can use bit fields in C/C++ that take up single bits; eight of them (one bit each) take up a single byte again.

kind regards,

Jos


Well that was the alternate way I'd do it, just generate one bit booleans myself, thanks.

MarkT

bit fields work in structs, each _individual_ variable must be addressable and thus is at least a byte (the unit
of addressing).
[ I won't respond to messages, use the forum please ]

majenko

Don't forget to pack your structs so that they take up the least space possible.  I also tend to unionise my bitfields so I have a handy byte / int / etc for setting them / clearing them en-masse:

Code: [Select]

struct flags {
  union {
    unsigned char value;
    struct {
      unsigned on:1;
      unsigned error:1;
      unsigned ping:1;
      unsigned rate:3;
      unsigned size:2;
    };
  };
} __attribute__((packed));

struct flags f;


f.on, f.error, f.ping will all take a 0 or 1, f.rate will take a number between 0 and 7, and f.size will take a number between 0 and 3 - and all in the space of a byte which can be accessed as f.value.

Go Up