Pages: [1]   Go Down
Author Topic: Boolean memory size  (Read 581 times)
0 Members and 1 Guest are viewing this topic.
Belgium
Offline Offline
Full Member
***
Karma: 0
Posts: 187
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged


Netherlands
Offline Offline
Full Member
***
Karma: 3
Posts: 102
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 34
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Try something like:

Serial.print(sizeof(boolean));

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

Belgium
Offline Offline
Full Member
***
Karma: 0
Posts: 187
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged


0
Online Online
Shannon Member
****
Karma: 198
Posts: 11625
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

bit fields work in structs, each _individual_ variable must be addressable and thus is at least a byte (the unit
of addressing).
Logged

[ I won't respond to messages, use the forum please ]

UK
Offline Offline
Faraday Member
**
Karma: 99
Posts: 4153
Where is your SSCCE?!?!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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.
Logged

Get 10% off all 4D Systems TFT screens this month: use discount code MAJENKO10

Pages: [1]   Go Up
Jump to: