How do you declare a data type with 1 bit size?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mjbauer95
    New Member
    • Jan 2009
    • 13

    How do you declare a data type with 1 bit size?

    How can you declare a data type with 1 bit size? So I can have a true boolean and not just an int or enum.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You can't. You could create a bit field structure, you can specify the size of the fields in a structure of bits fields in bits. However the compiler will round the type to at the minimum the nearest byte so you save nothing and the fields are not addressable and the order that bits in a bit field are stored is implementation defined.

    Generally bit firlds are best avoided, especially for portable code.

    If you want to store several boolean values in 1 byte then use the bitwise operators to directly access the bits in the byte, otherwise live with a 1 byte boolean.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Are you using C++?

      If so, try a bitset:

      Code:
      bitset<16> switches;
      That'll give you 16 addressable switches:

      Code:
      data.set(3) = true;  //set the 4th switch
      The size of the bitset will be 4 bytes (an int) so you could have 32 switches in a 4 byte field. More than that the bitset object will increase in size by the sizeof an int.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        The bool type in C99 acts like a 1-bit variable, but there is no telling how much storage space it actually takes up.

        Comment

        Working...