需要帮助读取二进制文件到结构 [英] Need help reading binary file to a structure
问题描述
我真的需要帮助这一个。我尝试下面的问题的解决方案,类似于我的,但输出是错误的。
I really need help on this one. I've tried following the solution of a question that was similar to mine, but the output is wrong.
文件是小端。我正在运行Win7,这也是小endian
The file is in little endian. I am running Win7, which is also little endian
我有一个struct Header,我想读取二进制文件到结构中。结构中的成员类型由问题定义。
I have a struct Header, and I want to read the binary file into the structure. The member types in the struct are defined by the problem.
struct Header
{
uint16_t marker;
uint8_t msg_type;
uint64_t sequence_id;
uint64_t timestamp;
uint8_t msg_direction;
uint16_t msg_len;
};
void parseFile()
{
Header h;
ifstream file("example_data_file.bin", std::ios::binary);
file.read((char*)&h, sizeof(h));
file.close();
printf("%u \n",(int)h.marker);
printf("%u \n",h.msg_type);
printf("%u \n", h.sequence_id);
printf("%u \n", h.timestamp);
printf("%u \n",h.msg_direction);
printf("%u \n",h.msg_len);
}
但是,输出没有意义。我预计第一行是ST,第二行是1,2或3.
However, the output is none sense. I am expecting the first row to be "ST", and the second row to be 1,2 or 3.
21587
1
1
3719304632
0
48
我也尝试过读这个struct的每个成员。
I have also tried reading each member of the struct individually like this
file.read ((char*)&h.marker, sizeof(h.marker));
file.read ((char*)&h.msg_type, sizeof(h.msg_type));
file.read ((char*)&h.sequence_id, sizeof(h.sequence_id));
file.read ((char*)&h.timestamp, sizeof(h.timestamp));
file.read ((char*)&h.msg_direction, sizeof(h.msg_direction));
file.read ((char*)&h.msg_len, sizeof(h.msg_len));
输出不同,但仍然错误。
The output is different, but it is still wrong.
以下是各个阅读的输出:
Here is the output of the individual reads:
21587
☺
1
1398642639377848
48
http://www.filedropper.com/exampledatafile
我不知道我做错了什么,我从来没有解析过二进制文件,所以这是我第一次做它。请帮助〜
I have no idea what im doing wrong, and I've never parsed a binary file before so this is my first time doing it. Please help~
谢谢!
推荐答案
打印数据的方式。很可能你的环境有
The error is in your way of printing the data. Likely, your environment has
typedef uint8_t char;
这是为什么您的 uint8_t
作为ASCII字符。类似地,ST
是 0x53 0x54
这是小端头的21587。
which is why your uint8_t
s get printed as an ASCII character. Similarly, "ST"
is 0x53 0x54
which is 21587 in little endian.
使用以下命令打印出来:
Use following to print it out:
printf("%c%c\n", *(char *)&(h.marker), *((char *)&(h.marker))+1);
printf("%u\n", (unsigned int)h.msg_type);
printf("%llu\n", h.sequence_id);
printf("%llu\n", h.timestamp);
printf("%u\n", (unsigned int)h.msg_direction);
printf("%hu\n", h.msg_len);
*(char *)&(h.marker)的简短说明
:
- 取地址
h.marker
:&(。h.marker)
- 解释为指向
char
:(char *)
- 取指针的内容:
*
(初始*)
- Take address of
h.marker
:&(.h.marker)
- Interpret it as a pointer to
char
:(char *)
- And take the pointer's content:
*
(the initial *)
这篇关于需要帮助读取二进制文件到结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!