Byte Order Problem--Analysis

Posted by stevenm187 on Thu, 03 Oct 2019 00:56:10 +0200

Now let's express this question from the beginning of the problem code.

#include <stdio.h>
#include <string.h>//memset
#include <stdlib.h>//free

#define uint8_t  unsigned char
#define uint16_t unsigned short
#define uint32_t unsigned int


typedef struct _ProtData
{
	uint8_t  POS11_head;
	uint8_t  POS12_num;
	uint8_t  POS13_rnum;
	uint16_t POS1415_len;
	uint16_t POS2122T;
	uint16_t POS2324L;
	uint8_t  POS25V[10];
	uint16_t POS31_CRC;
	
	uint16_t POS25Vlen;
}ProtData_T;

/*Universal Printing*/
void all_print(void* A,uint8_t len)
{
	for(uint8_t i=0;i<len;i++)
	printf("%02X ",*( (unsigned char*)A+i   )    );
	printf("\n");
}

void show_ProtData(ProtData_T *pag)
{
  printf("\n****************************************** \n");
  printf("pag->POS11_head= [%02X]\n" , pag->POS11_head);
  printf("pag->POS12_num= [%02X]\n" , pag->POS12_num);
  printf("pag->POS13_rnum= [%02X]\n" , pag->POS13_rnum);
  printf("pag->POS1415_len= [%04X]\n" , pag->POS1415_len);
  printf("pag->POS2122T= [%04X]\n" , pag->POS2122T);
  printf("pag->POS2324L= [%04X]\n" , pag->POS2324L);
  all_print(pag->POS25V,10);
  printf("pag->POS31_CRC= [%04X]\n" , pag->POS31_CRC);
  printf("\n****************************************** \n");
}



int main(int argc,char **argv)
{
	ProtData_T page;
    uint8_t pake[]={0XAA,0X01,0XFE,0X00,0X08,0X01,0X00,0X00,0X04,0X08,0XC0,0XC4,0X07,0X95,0X0A};
    memset(&page,0,sizeof(ProtData_T));
	memcpy(&page,pake,sizeof(pake));
	all_print(pake,sizeof(pake));
	show_ProtData(&page);

}

I'm trying to turn an organization into a structure where something goes wrong!

You can see that memory alignment is missing!

Because the structure has U8 and U16

What should I do?

IAR is

__packed  typedef struct _AppDataHeard
{
    uint8_t  FormAddr[6];
    uint16_t Handle;
    uint8_t  WriteType;
}AppDataHeardType;

SUBLIME can be

typedef   struct  __attribute__((packed)) _ProtData
{
	uint8_t  POS11_head;
	uint8_t  POS12_num;
	uint8_t  POS13_rnum;
	uint16_t POS1415_len;
	uint16_t POS2122T;
	uint16_t POS2324L;
	uint8_t  POS25V[10];
	uint16_t POS31_CRC;
	
	uint16_t POS25Vlen;
}ProtData_T;

No way

Change it to a purple one

#pragma pack(1)
typedef   struct  _ProtData
{
	uint8_t  POS11_head;
	uint8_t  POS12_num;
	uint8_t  POS13_rnum;
	uint16_t POS1415_len;
	uint16_t POS2122T;
	uint16_t POS2324L;
	uint8_t  POS25V[10];
	uint16_t POS31_CRC;
	
	uint16_t POS25Vlen;
}ProtData_T;
#pragma pack()

You can see that it's all right now! Every one has!!

 

Now the problem is that U16 needs to be exchanged!!

 

Topics: sublime