• KindaABigDyl@programming.dev
    link
    fedilink
    arrow-up
    149
    ·
    23 days ago
    typedef struct {
        bool a: 1;
        bool b: 1;
        bool c: 1;
        bool d: 1;
        bool e: 1;
        bool f: 1;
        bool g: 1;
        bool h: 1;
    } __attribute__((__packed__)) not_if_you_have_enough_booleans_t;
    
    • h4x0r@lemmy.dbzer0.com
      link
      fedilink
      English
      arrow-up
      14
      ·
      23 days ago

      This was gonna be my response to OP so I’ll offer an alternative approach instead:

      typedef enum flags_e : unsigned char {
        F_1 = (1 << 0),
        F_2 = (1 << 1),
        F_3 = (1 << 2),
        F_4 = (1 << 3),
        F_5 = (1 << 4),
        F_6 = (1 << 5),
        F_7 = (1 << 6),
        F_8 = (1 << 7),
      } Flags;
      
      int main(void) {
        Flags f = F_1 | F_3 | F_5;
        if (f & F_1 && f & F_3) {
          // do F_1 and F_3 stuff
        }
      }
      
    • mmddmm@lemm.ee
      link
      fedilink
      arrow-up
      131
      arrow-down
      4
      ·
      23 days ago

      And compiler. And hardware architecture. And optimization flags.

      As usual, it’s some developer that knows little enough to think the walls they see around enclose the entire world.

      • Lucien [he/him]@mander.xyz
        link
        fedilink
        arrow-up
        12
        arrow-down
        1
        ·
        23 days ago

        Fucking lol at the downvoters haha that second sentence must have rubbed them the wrong way for being too accurate.

      • timhh@programming.dev
        link
        fedilink
        arrow-up
        2
        arrow-down
        2
        ·
        22 days ago

        I don’t think so. Apart from dynamically typed languages which need to store the type with the value, it’s always 1 byte, and that doesn’t depend on architecture (excluding ancient or exotic architectures) or optimisation flags.

        Which language/architecture/flags would not store a bool in 1 byte?

        • brian@programming.dev
          link
          fedilink
          arrow-up
          1
          ·
          22 days ago

          things that store it as word size for alignment purposes (most common afaik), things that pack multiple books into one byte (normally only things like bool sequences/structs), etc

          • timhh@programming.dev
            link
            fedilink
            arrow-up
            1
            ·
            18 days ago

            things that store it as word size for alignment purposes

            Nope. bools only need to be naturally aligned, so 1 byte.

            If you do

            struct SomeBools {
              bool a;
              bool b;
              bool c;
              bool d;
            };
            

            its 4 bytes.

            • brian@programming.dev
              link
              fedilink
              arrow-up
              1
              ·
              18 days ago

              sure, but if you have a single bool in a stack frame it’s probably going to be more than a byte. on the heap definitely more than a byte

              • timhh@programming.dev
                link
                fedilink
                arrow-up
                1
                arrow-down
                1
                ·
                17 days ago

                but if you have a single bool in a stack frame it’s probably going to be more than a byte.

                Nope. - if you can’t read RISC-V assembly, look at these lines

                        sb      a5,-17(s0)
                ...
                        sb      a5,-18(s0)
                ...
                        sb      a5,-19(s0)
                ...
                

                That is it storing the bools in single bytes. Also I only used RISC-V because I’m way more familiar with it than x86, but it will do the same thing.

                on the heap definitely more than a byte

                Nope, you can happily malloc(1) and store a bool in it, or malloc(4) and store 4 bools in it. A bool is 1 byte. Consider this a TIL moment.

                • brian@programming.dev
                  link
                  fedilink
                  arrow-up
                  1
                  ·
                  16 days ago

                  c++ guarantees that calls to malloc are aligned https://en.cppreference.com/w/cpp/memory/c/malloc .

                  you can call malloc(1) ofc, but calling malloc_usable_size(malloc(1)) is giving me 24, so it at least allocated 24 bytes for my 1, plus any tracking overhead

                  yeah, as I said, in a stack frame. not surprised a compiler packed them into single bytes in the same frame (but I wouldn’t be that surprised the other way either), but the system v abi guarantees at least 4 byte alignment of a stack frame on entering a fn, so if you stored a single bool it’ll get 3+ extra bytes added on the next fn call.

                  computers align things. you normally don’t have to think about it. Consider this a TIL moment.

        • mmddmm@lemm.ee
          link
          fedilink
          arrow-up
          1
          arrow-down
          1
          ·
          22 days ago

          Apart from dynamically typed languages which need to store the type with the value

          You know that depending on what your code does, the same C that people are talking upthread doesn’t even need to allocate memory to store a variable, right?

            • timhh@programming.dev
              link
              fedilink
              arrow-up
              2
              ·
              18 days ago

              I think he’s talking about if a variable only exists in registers. In which case it is the size of a register. But that’s true of everything that gets put in registers. You wouldn’t say uint16_t is word-sized because at some point it gets put into a word-sized register. That’s dumb.

  • Lucy :3@feddit.org
    link
    fedilink
    arrow-up
    78
    ·
    23 days ago

    Then you need to ask yourself: Performance or memory efficiency? Is it worth the extra cycles and instructions to put 8 bools in one byte and & 0x bitmask the relevant one?

  • skisnow@lemmy.ca
    link
    fedilink
    English
    arrow-up
    41
    ·
    22 days ago

    Back in the day when it mattered, we did it like

    #define BV00		(1 <<  0)
    #define BV01		(1 <<  1)
    #define BV02		(1 <<  2)
    #define BV03		(1 <<  3)
    ...etc
    
    #define IS_SET(flag, bit)	((flag) & (bit))
    #define SET_BIT(var, bit)	((var) |= (bit))
    #define REMOVE_BIT(var, bit)	((var) &= ~(bit))
    #define TOGGLE_BIT(var, bit)	((var) ^= (bit))
    
    ....then...
    #define MY_FIRST_BOOLEAN BV00
    SET_BIT(myFlags, MY_FIRST_BOOLEAN)
    
    
    • Quatlicopatlix@feddit.org
      link
      fedilink
      arrow-up
      6
      ·
      22 days ago

      With embedded stuff its still done like that. And if you go from the arduino functionss to writing the registers directly its a hell of a lot faster.

    • ethancedwards8@programming.dev
      link
      fedilink
      English
      arrow-up
      2
      ·
      22 days ago

      Okay. Gen z programmer here. Can you explain this black magic? I see it all the time in kernel code but I have no idea what it means.

      • NιƙƙιDιɱҽʂ@lemmy.world
        link
        fedilink
        arrow-up
        4
        ·
        edit-2
        22 days ago

        It’s called bitshifting and is used to select which bits you want to modify so you can toggle them individually.

        1 << 0 is the flag for the first bit
        1 << 1 for the second
        1 << 2 for the third and so on

        I think that’s correct. It’s been years since I’ve used this technique tbh 😅

      • skisnow@lemmy.ca
        link
        fedilink
        English
        arrow-up
        3
        ·
        21 days ago

        The code is a set of preprocessor macros to stuff loads of booleans into one int (or similar), in this case named ‘myFlags’. The preprocessor is a simple (some argue too simple) step at the start of compilation that modifies the source code on its way to the real compiler by substituting #defines, prepending #include’d files, etc.

        If myFlags is equal to, e.g. 67, that’s 01000011, meaning that BV00, BV01, and BV07 are all TRUE and the others are FALSE.

        The first part is just for convenience and readability. BV00 represents the 0th bit, BV01 is the first etc. (1 << 3) means 00000001, bit shifted left three times so it becomes 00001000 (aka 8).

        The middle chunk defines macros to make bit operations more human-readable.

        Calling SET_BIT(myFlags, MY_FIRST_BOOLEAN) gets turned into ((myFlags) |= ((1 << 0))) , which could be simplified as myFlags = myFlags | 00000001 . (Ignore the flood of parentheses, they’re there for safety due to the loaded shotgun nature of the preprocessor.)

  • Subverb@lemmy.world
    link
    fedilink
    arrow-up
    34
    ·
    edit-2
    23 days ago

    The 8-bit Intel 8051 family provides a dedicated bit-addressable memory space (addresses 20h-2Fh in internal RAM), giving 128 directly addressable bits. Used them for years. I’d imagine many microcontrollers have bit-width variables.

    bit myFlag = 0;

    Or even return from a function:

    bit isValidInput(unsigned char input) { // Returns true (1) if input is valid, false (0) otherwise return (input >= '0' && input <= '9'); }

    • the_tab_key@lemmy.world
      link
      fedilink
      arrow-up
      11
      ·
      23 days ago

      We could go the other way as well: TI’s C2000 microcontroller architecture has no way to access a single byte, let alone a bit. A Boolean is stored in 16-bits on that one.

  • acockworkorange@mander.xyz
    link
    fedilink
    arrow-up
    33
    ·
    22 days ago

    In the industrial automation world and most of the IT industry, data is aligned to the nearest word. Depending on architecture, that’s usually either 16, 32, or 64 bits. And that’s the space a single Boolean takes.

    • ZILtoid1991@lemmy.world
      link
      fedilink
      arrow-up
      16
      ·
      22 days ago

      That’s why I primarily use booleans in return parameters, beyond that I’ll try to use bitfields. My game engine’s tilemap format uses a 32 bit struct, with 16 bit selecting the tile, 12 bit selecting the palette, and 4 bit used for various bitflags (horizontal and vertical mirroring, X-Y axis invert, and priority bit).

      • acockworkorange@mander.xyz
        link
        fedilink
        arrow-up
        25
        ·
        22 days ago

        Bit fields are a necessity in low level networking too.

        They’re incredibly useful, I wish more people made use of them.

        I remember I interned at a startup programming microcontrollers once and created a few bitfields to deal with something. Then the lead engineer went ahead and changed them to masked ints. Because. The most aggravating thing is that an int size isn’t consistent across platforms, so if they were ever to change platforms to a different word length, they’d be fucked as their code was full of platform specific shenanigans like that.

        /rant

        • ulterno@programming.dev
          link
          fedilink
          English
          arrow-up
          3
          ·
          22 days ago

          Yeah. I once had to do stuff to code that had bit-fields like that and after a while, realised (by means of StackOverflow) that that part is UB and I had to go with bitwise operations instead.

        • Croquette@sh.itjust.works
          link
          fedilink
          arrow-up
          2
          ·
          21 days ago

          I always use stdint.h so that my types are compatible across any mcu. And it makes the data type easily known instead of guessing an i t size

    • Gsus4@mander.xyz
      link
      fedilink
      arrow-up
      11
      ·
      edit-2
      23 days ago

      Weird how I usually learn more from the humor communities than the serious ones… 😎

    • borokov@lemmy.world
      link
      fedilink
      arrow-up
      2
      ·
      21 days ago
      auto v = std::vector<bool>(8);
      bool* vPtr = v.data;
      vPtr[2] = true;
      // KABOOM !!!
      

      I’ve spent days tracking this bug… That’s how I learned about bool specialisation of std::vector.

  • JakenVeina@lemm.ee
    link
    fedilink
    English
    arrow-up
    23
    arrow-down
    2
    ·
    23 days ago

    It’s far more often stored in a word, so 32-64 bytes, depending on the target architecture. At least in most languages.

    • timhh@programming.dev
      link
      fedilink
      arrow-up
      5
      ·
      edit-2
      22 days ago

      No it isn’t. All statically typed languages I know of use a byte. Which languages store it in an entire 32 bits? That would be unnecessarily wasteful.

      • JakenVeina@lemm.ee
        link
        fedilink
        English
        arrow-up
        1
        ·
        16 days ago

        C, C++, C#, to name the main ones. And quite a lot of languages are compiled similarly to these.

        To be clear, there’s a lot of caveats to the statement, and it depends on architecture as well, but at the end of the day, it’s rare for a byte or bool to be mapped directly to a single byte in memory.

        Say, for example, you have this function…

        public void Foo()
        {
            bool someFlag = false;
            int counter = 0;
        
            ...
        }
        

        The someFlag and counter variables are getting allocated on the stack, and (depending on architecture) that probably means each one is aligned to a 32-bit or 64-bit word boundary, since many CPUs require that for whole-word load and store instructions, or only support a stack pointer that increments in whole words. If the function were to have multiple byte or bool variables allocated, it might be able to pack them together, if the CPU supports single-byte load and store instructions, but the next int variable that follows might still need some padding space in front of it, so that it aligns on a word boundary.

        A very similar concept applies to most struct and object implementations. A single byte or bool field within a struct or object will likely result in a whole word being allocated, so that other variables and be word-aligned, or so that the whole object meets some optimal word-aligned size. But if you have multiple less-than-a-word fields, they can be packed together. C# does this, for sure, and has some mechanisms by which you can customize field packing.

        • timhh@programming.dev
          link
          fedilink
          arrow-up
          1
          arrow-down
          1
          ·
          16 days ago

          No, in C and C++ a bool is a byte.

          since many CPUs require that for whole-word load and store instructions

          All modern architectures (ARM, x86 RISC-V) support byte load/store instructions.

          or only support a stack pointer that increments in whole words

          IIRC the stack pointer is usually incremented in 16-byte units. That’s irrelevant though. If you store a single bool on the stack it would be 1 byte for the bool and 15 bytes of padding.

          A single byte or bool field within a struct or object will likely result in a whole word being allocated, so that other variables and be word-aligned

          Again, no. I think you’ve sort of heard about this subject but haven’t really understood it.

          The requirement is that fields are naturally aligned (up to the machine word size). So a byte needs to be byte-aligned, 2-bytes needs to be 2-byte aligned, etc.

          Padding may be inserted to achieve that but that is padding it doesn’t change the size of the actual bool, and it isn’t part of the bool.

          But if you have multiple less-than-a-word fields, they can be packed together.

          They will be, if it fits the alignment requirements. Create a struct with 8 bools. It will take up 8 bytes no matter what your packing setting is. They even give an example:

          If you specify the default packing size, the size of the structure is 8 bytes. The two bytes occupy the first two bytes of memory, because bytes must align on one-byte boundaries.

          They used byte here but it’s the same for bool because a bool is one byte.

          I’m really surprised how common this misconception is.

      • Aux@feddit.uk
        link
        fedilink
        English
        arrow-up
        1
        arrow-down
        1
        ·
        21 days ago

        It’s not wasteful, it’s faster. You can’t read one byte, you can only read one word. Every decent compiler will turn booleans into words.

        • timhh@programming.dev
          link
          fedilink
          arrow-up
          1
          arrow-down
          1
          ·
          18 days ago

          You can’t read one byte

          lol what. You can absolutely read one byte: https://godbolt.org/z/TeTch8Yhd

          On ARM it’s ldrb (load register byte), and on RISC-V it’s lb (load byte).

          Every decent compiler will turn booleans into words.

          No compiler I know of does this. I think you might be getting confused because they’re loaded into registers which are machine-word sized. But in memory a bool is always one byte.

              • Aux@feddit.uk
                link
                fedilink
                English
                arrow-up
                1
                arrow-down
                1
                ·
                16 days ago

                Internally it will still read a whole word. Because the CPU cannot read less than a word. And if you read the ARM article you linked, it literally says so.

                Thus any compiler worth their salt will align all byte variables to words for faster memory access. Unless you specifically disable such behaviour. So yeah, RTFM :)

                • timhh@programming.dev
                  link
                  fedilink
                  arrow-up
                  1
                  arrow-down
                  1
                  ·
                  16 days ago

                  Wrong again. It depends on the CPU. They can absolutely read a single byte and they will do if you’re reading from non-idempotent memory.

                  If you’re reading from idempotent memory they won’t read a byte or a word. They’ll likely read a whole cache line (usually 64 bytes).

                  And if you read the ARM article you linked, it literally says so.

                  Where?

                  Thus any compiler worth their salt will align all byte variables to words for faster memory access.

                  No they won’t because it isn’t faster. The CPU will read the whole cache line that contains the byte.

                  RTFM

                  Well, I would but no manual says that because it’s wrong!

  • glitchdx@lemmy.world
    link
    fedilink
    English
    arrow-up
    21
    arrow-down
    2
    ·
    23 days ago

    if wasting a byte or seven matters to you, then then you need to be working in a lower level language.

  • SW42@lemmy.world
    link
    fedilink
    arrow-up
    18
    ·
    23 days ago

    Joke’s on you, I always use 64 bit wide unsigned integers to store a 1 and compare to check for value.