如何将大端结构转换为小端结构? [英] How do I convert a big-endian struct to a little endian-struct?

查看:1260
本文介绍了如何将大端结构转换为小端结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在UNIX机器上创建的二进制文件。这只是一堆接一条记录的记录。记录定义如下:

I have a binary file that was created on a unix machine. It's just a bunch of records written one after another. The record is defined something like this:

struct RECORD {
  UINT32 foo;
  UINT32 bar;
  CHAR fooword[11];
  CHAR barword[11];
  UNIT16 baz;
}



我试图找出如何读取和解释这些数据Windows机器。我有这样的:

I am trying to figure out how I would read and interpret this data on a Windows machine. I have something like this:

fstream f;
f.open("file.bin", ios::in | ios::binary);

RECORD r;

f.read((char*)&detail, sizeof(RECORD));

cout << "fooword = " << r.fooword << endl;

我得到了一堆数据,但它不是我期望的数据。我怀疑我的问题与机器的端差有关,所以我来问这个问题。

I get a bunch of data, but it's not the data I expect. I'm suspect that my problem has to do with the endian difference of the machines, so I've come to ask about that.

我知道多个字节将会存储在windows上的little-endian和unix环境中的big-endian,我得到。对于两个字节,Windows上的0x1234将在unix系统上为0x3412。

I understand that multiple bytes will be stored in little-endian on windows and big-endian in a unix environment, and I get that. For two bytes, 0x1234 on windows will be 0x3412 on a unix system.

字节序是否影响结构体作为整体或结构体的每个成员的字节顺序?我需要什么方法来将在UNIX系统上创建的结构转换为在Windows系统上具有相同数据的结构?

Does endianness affect the byte order of the struct as a whole, or of each individual member of the struct? What approaches would I take to convert a struct created on a unix system to one that has the same data on a windows system? Any links that are more in depth than the byte order of a couple bytes would be great, too!

推荐答案

除了一个字节的字节顺序, endian,你需要知道两个平台之间的填充差异。特别是如果你有奇数长度的字符数组和16位的值,你可能会发现不同数量的pad字节之间的一些元素。

As well as the endian, you need to be aware of padding differences between the two platforms. Particularly if you have odd length char arrays and 16 bit values, you may well find different numbers of pad bytes between some elements.

编辑:如果结构被写出没有包装,那么应该是相当直接。类似这样(未测试的)代码应该做的工作:

if the structure was written out with no packing, then it should be fairly straightforward. Something like this (untested) code should do the job:

// Functions to swap the endian of 16 and 32 bit values

inline void SwapEndian(UINT16 &val)
{
	val = (val<<8) | (val>>8);
}

inline void SwapEndian(UINT32 &val)
{
	val = (val<<24) | ((val<<8) & 0x00ff0000) |
		  ((val>>8) & 0x0000ff00) | (val>>24);
}

然后,一旦加载了struct,只需交换每个元素: / p>

Then, once you've loaded the struct, just swap each element:

SwapEndian(r.foo);
SwapEndian(r.bar);
SwapEndian(r.baz);

这篇关于如何将大端结构转换为小端结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆