开发者

Reverse reading WORD from a binary file?

I have a structure:

struct JFIF_HEADER
{
    WORD marker[2];        // = 0xFFD8FFE0
    WORD length;           // = 0x0010
    BYTE signature[5];     // = "JFIF\0"
    BYTE versionhi;        // = 1
    BYTE versionlo;        // = 1
    BYTE xyunits;          // = 0
    WORD xdensity;         // = 1
    WORD ydensity;         // = 1
    BYTE thumbnwidth;      // = 0
    BYTE thumbnheight;     // = 0
};

This is how I read it from the file:

HANDLE file = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ,
                         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
DWORD tmp = 0;
DWORD size = GetFileSize(file, &tmp);
BYTE *DATA = new BYTE[size];
ReadFile(file, DATA, size, &tmp, 0);

JFIF_HEADER header;
memcpy(&header, DATA, sizeof(JFIF_HEADER));

This is how the beginning of my file looks in hex editor:

0xFF 0xD8 0xFF 0xE0 0x00 0x10 0x4A 0x46 0x49 0x46 0x00 0x01 0x01 0x00 0x00 0x01

When I print header.marker, it shows exactly what it should (0xFFD8FFE0). But when I print header.length开发者_StackOverflow, it shows 0x1000 instead of 0x0010. The same thing is with xdensity and ydensity. Why do I get wrong data when reading a WORD?


You are on an x86 cpu which stores words low byte-high byte (little endian) The binary file is presumably stored in big endian.

You need to manually swap each byte in the file (or possibly your JFIF library will do this for you)

ps. The safest way to swap bytes is to use the ntohs() and htons() macros in your 'C' library. See the wiki article for the details of endianness

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜