在 C 中将字节解析为结构体属性 (int16_t)

发布于 01-17 03:40 字数 972 浏览 2 评论 0原文

我正在尝试解析这些字节:

00000000: 4353 4333 3630 4653 >0200< >0000 1900< 0000

分别解析为 uint16_tuint32_t 结构属性。

手头的结构:

typedef struct __packed {
uint8_t fs_id [8];
uint16_t block_size;
uint32_t file_system_block_count;
uint32_t fat_start_block;
//and so on

Selbie 的解决方案中汲取灵感,我写道:

read(file_descriptor, &blk.fs_id, sizeof(blk.fs_id));
read(file_descriptor, &blk.block_size, sizeof(blk.block_size));
read(file_descriptor, &blk.file_system_block_count, sizeof(blk.file_system_block_count));
// and so on for additional attributes.

不幸的是,在调试 block_size 当它应该保存 uint16_t 512 时,它仅保存值“2”。同样,file_system_block_count 在应该保存“6400”时却保存了“1638400”:(

如何让 read() 函数在“”之后包含“00” 02”,因此将其读为 512?我想它可能需要 memcpy()

I am trying to parse these bytes:

00000000: 4353 4333 3630 4653 >0200< >0000 1900< 0000

Into uint16_t and uint32_t struct attributes respectively.

The struct at hand:

typedef struct __packed {
uint8_t fs_id [8];
uint16_t block_size;
uint32_t file_system_block_count;
uint32_t fat_start_block;
//and so on

Taking inspiration from Selbie's solution I've written:

read(file_descriptor, &blk.fs_id, sizeof(blk.fs_id));
read(file_descriptor, &blk.block_size, sizeof(blk.block_size));
read(file_descriptor, &blk.file_system_block_count, sizeof(blk.file_system_block_count));
// and so on for additional attributes.

Unfortunately, upon debugging block_size is only holding the value "2" when it is supposed to be holding uint16_t 512. Similarly, file_system_block_count is holding "1638400" when it should be holding "6400" :(

How do I get the read() function to include the "00" after the "02" and therefore read it as 512? I'd imagine it may require memcpy()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮生未歇2025-01-24 03:40:22

感谢@barmar,需要分别对 16 位和 32 位的 htons()htonl() 进行简单调用。

memcpy(&blk.block_size, buf+8, 2);
blk.block_size = htons(blk.block_size);

memcpy(&blk.file_system_block_count, buf+10, 4);
blk.file_system_block_count = htonl(blk.file_system_block_count);

这导致 blk.block_sizeblk.file_system_block_count 分别正确地保存值“512”和“6400”。

Thanks to @barmar a simple call to htons() and htonl() for 16-bit and 32-bit respectivley is required.

memcpy(&blk.block_size, buf+8, 2);
blk.block_size = htons(blk.block_size);

memcpy(&blk.file_system_block_count, buf+10, 4);
blk.file_system_block_count = htonl(blk.file_system_block_count);

This results in blk.block_size and blk.file_system_block_count correctly holding the value "512" and "6400" respectively.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文