Q: typecast binary to struct I've read about how structs are stored in memory and came up with an idea to typecast binary data directly to struct. I tried to typecast to normal struct type, but the compiler complained that typecast to only pointer types is valid (see first line of main). Why is that?
After that, I used a pointer to struct typecast which apparently succeeded. When I try to access the variables of struct, I get a silent erroneous exit code 11. What is the correct way to typecast binary to struct? Or any other type, such as array.. Is this concept possible in C?
typedef unsigned char UINT8;
struct L{
    UINT8 ui8:4;
    UINT8 ui8v2:4;
    UINT8 ui8v3;
    UINT8 ui8v4;
};
typedef struct L L, *PL;

int main(){
    // L myStruct = (L)0b000000010000000000000001;  gives error => pointer type required
    PL pMyStruct = (PL)0b000000010000000000000001; // compiles normally
    printf("ui8: %d", pMyStruct->ui8); // but returns error code 11 at runtime

}


A: There is no portable way of typecasting one type to the data typed like structs.
You can pune the type using pointers, structs or using memcpy but it is not portable and might break the strict aliasing rules:
Example https://godbolt.org/z/bNH7Vc:
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

#include <string.h>


typedef struct {
    uint8_t ui8:4;
    uint8_t ui8v2:4;
    uint8_t ui8v3;
    uint8_t ui8v4;
}L;

int main(){
    unsigned val = 0b000000010000000000000001;
    L *myStructPtr = (L *)&val;
    L myStruct;

    memcpy(&myStruct, &val, sizeof(myStruct));

    printf("0x%02x \n", myStructPtr -> ui8);
    printf("0x%02x \n", myStructPtr -> ui8v2);
    printf("0x%02x \n", myStructPtr -> ui8v3);
    printf("0x%02x \n----\n", myStructPtr -> ui8v4);

    printf("0x%02x \n", myStruct.ui8);
    printf("0x%02x \n", myStruct.ui8v2);
    printf("0x%02x \n", myStruct.ui8v3);
    printf("0x%02x \n", myStruct.ui8v4);
}

