在 C 中将字节解析为结构体属性 (int16_t)
我正在尝试解析这些字节:
00000000: 4353 4333 3630 4653 >0200< >0000 1900< 0000
分别解析为 uint16_t
和 uint32_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 技术交流群。

感谢@barmar,需要分别对 16 位和 32 位的
htons()
和htonl()
进行简单调用。这导致
blk.block_size
和blk.file_system_block_count
分别正确地保存值“512”和“6400”。Thanks to @barmar a simple call to
htons()
andhtonl()
for 16-bit and 32-bit respectivley is required.This results in
blk.block_size
andblk.file_system_block_count
correctly holding the value "512" and "6400" respectively.