i have following legacy code:
#define uint8 unsigned char #define uint16 unsigned short #define uint32 unsigned long typedef union { struct { uint16 r1: 1; uint16 s1: 1; uint16 s2: 1; uint16 d1: 1; uint16 i1: 1; uint16 s3: 1; uint16 s4: 1; uint16 s5: 1; uint16 s6: 1; uint16 p1: 1; uint16 f1: 1; uint16 i2: 1; uint16 r2: 4; }bb; uint16 v16; }test_union11; typedef struct /* memory index */ { /* ++++++++++++ */ // write config 01-32 uint16 i1; /* 0 */ uint16 i2; /* 2 */ // faults uint16 o3; /* 4 */ uint16 o4; /* 6 */ uint16 o5; /* 8 */ uint16 o6; /* 10 */ // values 01-08 uint8 o7; /* 12 */ uint8 o8; /* 13 */ uint8 o9; /* 14 */ uint8 o10; /* 15 */ uint8 o11; /* 16 */ uint8 o12; /* 17 */ uint8 o13; /* 18 */ uint8 o14; /* 19 */ // values 09-12 uint16 o15; /* 20 */ uint16 o16; /* 22 */ uint16 o17; /* 24 */ uint16 o18; /* 26 */ // values 13-14 uint32 o19; /* 28 */ uint32 o20; /* 32 */ uint8 octstr[8]; } test_str11; test_str11 test_str1; test_union11 test_union; int test_memcpy(void) { test_str1.o15 = 1500; test_union.v16 = test_str1.i1; memcpy(&test_union,&test_str1,sizeof(test_union11)); } int main(void) { test_memcpy(); printf("test pass!\n"); return 0; } is idea behind line test_union.v16 = test_str1.i1 test_union.bb nested structure filled data structure "test_str1"? reason neither after line nor after memcpy happened. why? , meaning of numbers in nested structure inside union?
i tested case when there no such numbers smaller union , structure , memcpy worked out, though trick first element assignment didn't. syntax that:
un = (*(test_union1*)&st); also worked out second test, , didn't code presented. difference between 2 expressions? , test_union.v16 = test_str1.i1 copy i1 variable or many bytes test_union.bb can hold?
the code should work on stm32f10x embedded platform, though it's not working in visual studio on pc @ moment. therefore pure c problem. thanks!
you have not assigned test_str.i1. if do, think program work. idea of union provide easy way @ 16 bits in unsigned int v16. however, platform dependant code, because int may not 16 bits (it 32 bits).
the size of union size of largest member. however, not sure alignment rules size mis-matches.
finally, think best way @ bits using bit-wise operators &, | etc.
Comments
Post a Comment