Search code examples
cstructurebit-fields

Which bits are which in a struct with bitfields?


#include <string.h>
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

typedef struct AA {
    int a1:5;
    int a2:2;
} AA;

int main() {
    AA aa;
    char cc[100];
    strcpy(cc, "0123456789");
    memcpy(&aa, cc, sizeof(AA));
    printf("%d\n", aa.a1);
    printf("%d\n", aa.a2);
    return 0;
}

I mean I know that sizeof(AA) is sizeof(int) equals 4 byte, and after copying "0123" to aa the binary number is

00110011,00110010,00110001,00110000
    3         2        1         0

but i don't understand which bits are a1:5 or a2:2?


Solution

  • The arrangements of bitfields is not standardized.

    Based on your results, a1 holds 10000 and a2 holds 01. One way this could arise is if a1 is the lowest 5 bits of cc[0] and a2 is the next-lowest 2 bits .

    That is, cc[0] is 00110000 which is being divided as 0 01 10000 .

    If you did some more experimentation with values you could find out for sure which order your compiler is using.