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?
 
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;
}
 
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

Similar Threads

template and bit-field 0
size of bit field 0
size of bit field 1
bit fields and data structure 7
On bit fields usage 9
bit field usage question 3
Array of 4 bit fields? 9
Bit Field Question 5

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top