8 bit bit field?


J

JustSomeGuy

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?
 
Ad

Advertisements

B

Bob Hairgrove

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?

#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;
}
 
Ad

Advertisements

V

Victor Bazarov

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

#pragma pack(1)
^^^^^^^^^^^^^^^
This is implementation-defined.
typedef struct
{
unsigned int item_len;
unsigned char presentationContextID;
unsigned char unused : 6;
unsigned char command : 1;
unsigned char last : 1;
} pdv_type;

You're not in C any more, just use normal C++ syntax:

struct 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?

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
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Top