cparsingbyteuint

Parse Bytes Into Struct Attribute (int16_t) In C


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()?


Solution

  • 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.