#include <stdio.h>
typedef struct _octet
{
char tft_op:3;
char e_bit:1;
char no_of_pkt:4;
}octet_t;
int main()
{
octet_t st_octet;
st_octet.tft_op = 0x8;
st_octet.e_bit = 0x1;
st_octet.no_of_pkt = 0x10;
char *ptr = (char*)&st_octet;
printf("%#x\n",*ptr);
return 0;
}
here i want to store 3 bits in tft_op, 1 bit e_bit, 4 bits in no_of_pkt, but i want the o/p as a combined 1 byte i.e is want the o/p as FA but the o/p i get is 0x8 what should i do to get the o/p as FA
Your values are too big for the allocated space:
So, the effective result is:
which is what you’re getting. 0xfa is:
but you assume that the first item in the structure is at bit position 7 (the most significant) but the standard (as far as I know) doesn’t specify where the bits should start (it could be bit0, the least significant) and looking at your output I guess the first field is the least significant bit, so you have:
where a is tft_op, b is e_bit and c is no_of_pkt. To get 0xfa it’s either:
or, if the order is the other way round:
Also, rather than doing
char *ptr = (char*)&st_octet;look into using a union: