Go Down

Topic: Boolean memory size (Read 884 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 will NOT respond to personal messages, I WILL delete them, 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
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy