Has anyone created a method for using a byte as 8 boolean variables in C? I could implement it myself, but I'm curious, as it seems that the usual is to use a whole int for logical values. What I mean is something like this:
bool a;
bool b;
bool c;
bool d;
bool e;
bool f;
bool g;
bool h;
bool i;
And from a to h it would use just one byte, but when it's going to allocate memory for i it would the first bit from another byte. Also, is this how C++ implements its boolean types, or does it use a integer per boolean variable?
Other people also prefer to cache the 1 << flag_number like this:
#define FLAG_1 0x00000001
#define FLAG_2 0x00000002
#define FLAG_3 0x00000004
#define FLAG_4 0x00000008
#define FLAG_5 0x00000010
...
#define FLAG_32 0xF0000000
And they can just do if (flags & FLAG_n) ... to test for a specific flag. flags |= FLAG_n; to set it.
>>1 Has anyone created a method for using a byte as 8 boolean variables in C?
First of all, 10/10 IHBT, A+ would be trolled again etc.
Secondly... People have been doing this for the entire history of computer programming. I hope that you are a relatively new programmer, otherwise I will have to slap you for not knowing that everyone already started doing this decades ago.
#include <stdio.h>
#include <stdint.h>
#define BITSET(v, bit) (v |= (1 << bit))
#define BITCLEAR(v, bit) (v &= ~(1 << bit))
#define ISBIT(v, bit) (v & (1 << bit))
#define BITTOGGLE(v, bit) (v ^= (1 << bit))
int main(void) {
uint8_t n = 0;
if (ISBIT(n, 0)) { // false
printf("Bit 0 is set in the value %i.\n", n);
}
BITSET(n, 0);
if (ISBIT(n, 0)) { // true
printf("Bit 0 is set in the value %i.\n", n);
}
n = 255;
BITTOGGLE(n, 7);
printf("255, but with bit7 toggled off == %i\n", n);
return 0;
}