Pages: [1]   Go Down
Author Topic: Boolean memory size  (Read 417 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
Jr. Member
**
Karma: 2
Posts: 67
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: 33
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
Offline Offline
Shannon Member
****
Karma: 162
Posts: 10523
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: 92
Posts: 3969
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

Why not visit my eBay shop? http://stores.ebay.co.uk/Majenko-Technologies
Replacement for the Arduino IDE: UECIDE - Proper serial terminal, graphing facilities, plugins, overhauled internals.
Java isn't bad in itself, but it has enabled morons to write programs.

Pages: [1]   Go Up
Jump to: