0

I have 8 bytes string with flags, some of them are booleans and some are chars. What I want is access that flags by it's names in my code, like myStruct.value1

I created some struct according to my wishes. I would expect I can split the string into that struct as both have size of 64 bits in total.

// destination
typedef struct myStruct_t {
  uint8_t  value1  : 8;
  uint8_t  value2  : 8;
  uint16_t value3  : 16;
  uint8_t  value4  : 8;
  uint8_t  value5  : 1;
  uint8_t  value6  : 1;
  uint8_t  value7  : 1;
  uint8_t  value8  : 1;
  uint8_t  value9  : 1;
  uint16_t value10 : 11;
  uint8_t  value11 : 8;
} myStruct_t;

// source
char buf[8] = "12345678";

// read about strcpy and memcpy but doesn't work
memcpy(myStruct, buf, 8);

However it does not work and i get following error message:

error: cannot convert 'myStruct_t' to 'void*' for argument '1' to 'void* memcpy(void*, const void*, size_t)'
     memcpy(myStruct, buf, 8);
                            ^
alecxs
  • 701
  • 8
  • 17
  • C++ is not C. Your code suggests that you may be teaching yourself C. – Drew Dormann Jul 23 '21 at 15:32
  • 1
    `myStruct = buf` will fail because `myStruct` is nowhere defined. Assuming that `myStruct_t myStruct` is declared, still, `buf` has a conflicting type. The code looks like C but is tagged as C++. Therefore, `char buf[8]` needs one extra space, i.e. 9. – Rohan Bari Jul 23 '21 at 16:17

2 Answers2

1

memcpy expects its first two arguments to be pointers.

Arrays like your buf will implicitly decay to pointers, but your type myStruct_t will not.

myStruct_t myStruct;
memcpy(&myStruct, buf, 8);
//     ^ produces a POINTER to myStruct
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
0

If I understand correctly what you are trying to do, I would first convert the 8 character buffer to binary. Then, you can extract substrings from it for the length of each of the values you want. Finally, you can convert the binary strings to their numerical values.

Also, you should make your char array size 9. You need an extra character for the null terminator. The way you have it currently won't compile.

Sean
  • 49
  • 4
  • can you elaborate more? have trouble on value3 (guess related to [compiler](https://stackoverflow.com/q/6043483) padding) memcpy does not always map right – alecxs Aug 05 '21 at 21:32