8 bit bit field?

Discussion in 'C++' started by JustSomeGuy, Feb 27, 2006.

  1. JustSomeGuy

    JustSomeGuy Guest

    I have an 8 bit byte in which two bits are used and the remaining 6 are
    unused.

    #pragma pack(1)
    typedef struct
    {
    unsigned int item_len;
    unsigned char presentationContextID;
    unsigned char unused : 6;
    unsigned char command : 1;
    unsigned char last : 1;
    } pdv_type;

    Does this syntax look correct?
    unused bits 7,6,5,4,3,2
    command bit 1
    last bit 0

    Will the compiler try to put the bit field into a 16 or 32 bit holder?
     
    JustSomeGuy, Feb 27, 2006
    #1
    1. Advertisements

  2. #include <iostream>
    #include <ostream>

    #pragma pack(1)
    typedef struct
    {
    unsigned int item_len;
    unsigned char presentationContextID;
    unsigned char unused : 6;
    unsigned char command : 1;
    unsigned char last : 1;
    } pdv_type;

    int main() {
    using namespace std;
    cout << "Size of pdv_type: " << sizeof(pdv_type) << endl;
    return 0;
    }
     
    Bob Hairgrove, Feb 27, 2006
    #2
    1. Advertisements

  3. ^^^^^^^^^^^^^^^
    This is implementation-defined.
    You're not in C any more, just use normal C++ syntax:

    struct pdv_type
    {
    ...
    };
    Allocation and alignment are implementation-defined. If you want to
    make sure that it's bits 0 and 1 that you're using and the allocation is
    actually 1 byte, you need to write

    unsigned char mybitstuff;

    bool command() const { return mybitstuff & 1; }
    bool last() const { return (mybitstuff >> 1) & 1; }
    void set_command(bool b)
    { if (b) mybitstuff |= 1; else mybitstuff &= ~1; }
    void set_last(bool b)
    { if (b) mybitstuff |= 2; else mybitstuff &= ~2; }

    i.e. make the actual things _an_interface_ instead of naked data.

    V
     
    Victor Bazarov, Feb 27, 2006
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.