简体   繁体   English

fwrite'ing 结构导致混合数据被保存

[英]fwrite'ing a struct results in mixed data being saved

I'm obtaining data from an accelerometer and trying to log it to a file.我正在从加速度计获取数据并尝试将其记录到文件中。 However, I'm a little perplexed by the output I'm getting.但是,我对得到的 output 有点困惑。 I'm only logging one sample to ensure the data is written correctly.我只记录一个样本以确保数据写入正确。

I've created the following struct to group data:我创建了以下结构来对数据进行分组:

struct AccData
{
    int16_t x;
    int16_t y;
    int16_t z;
    unsigned int time;
};

The above should amount to 10 bytes in total.以上总共应为 10 个字节。

I'm writing to stdout and getting the following data from the sensor:我正在写入标准输出并从传感器获取以下数据:

I (15866) Accelerometer: Measurement: X 25 Y 252 Z 48 Time: 10 I (15866) 加速度计:测量:X 25 Y 252 Z 48时间: 10

The data that's stored to the sd card looks like so:存储到 sd 卡的数据如下所示:

1900FC00300000000A00 1900FC00300000000A00

Splitting those up gives us:把它们分开给我们:

1900 FC00 3000 00000A00 1900 FC00 3000 00000A00

This is where I'm starting to get confused.这是我开始感到困惑的地方。 The first 3 sectors only make sense if I reverse the order of the bytes such that:前 3 个扇区只有在我颠倒字节顺序时才有意义:

X X Y Z Z Time时间
1900 -> 0019 = 25 1900 -> 0019 = 25 3000 -> 0030 = 48 00000A00 -> 000A0000 = 655.360

First, this may be due to my limited C knowledge, but is it normal for the output to be swapped like above?首先,这可能是由于我对C的了解有限,但是output像上面这样交换正常吗?

Additionally, I can't get the time to make sense at all.此外,我根本没有时间去理解。 It almost looks like only 3 bytes are being allocated for the unsigned integer, which would give the correct result if you didn't reverse it.看起来几乎只为未签名的 integer 分配了 3 个字节,如果您不反转它,它会给出正确的结果。

Like @Someprogrammerdude pointed out in the comments, this had to do with endianess and the fact that my struct was being padded, resulting in the struct being 12 bits instead of 10.就像@Someprogrammerdude 在评论中指出的那样,这与字节序和我的结构被填充的事实有关,导致结构为 12 位而不是 10 位。

Accounting for the padding the data now looks like so: 1900FC00 30000000 0A000000,考虑到填充,数据现在看起来像这样:1900FC00 30000000 0A000000,

Reading above with little endian made it make sense.用小端阅读上面的内容是有道理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM