I should read data from a pcap file to an array, and then convert it to a struct pointer.
and there is a problem of endian.
there is my code
#include "stdio.h"
#pragma pack(1)
struct header
{
unsigned char len:4;
unsigned char version:4;
unsigned short pkg_len;
unsigned short pkg_flag;
};
int main()
{
// assume i read 5 bytes from a file into array a.
unsigned char a [] = {0x45, 0xff, 0x08, 0xee, 0x09};
header *i = (header *)&a;
printf("%02hx %02hx %02hx %02hx\n", i->version, i->len, i->pkg_len, i->pkg_flag);
return 0;
}
it printed :
04 05 08ff 09ee
however, what i want is :
04 05 ff08 ee09
what should i do ? thank you very much!
header i[]={{4,5,0xff08,0xee09}}?%xexpects anunsigned intas input by default, so you need to cast your values when passing them toprintf. In the case of theunsigned shortfields, you can use%hxwithout casting.headerstruct? Endianness ofshortfields may be solved withhtons, but there's no built-in function to swap order within a single byte. Anyway, that would be a lot implementation and device specific, so don't expect any portability.