cochran_emc.h: packed structs

Lubomir I. Ivanov neolit123 at gmail.com
Tue Oct 28 13:50:17 PDT 2014


On 28 October 2014 21:26, Jef Driesen <jef at libdivecomputer.org> wrote:
> On 28-10-14 17:32, Dirk Hohndel wrote:
>>
>> The reason so many people reverse engineering want packed structures is
>> that it makes it so much easier to write readable code.
>>
>> A typical 8 byte sample might look like this:
>>
>> struct sample {
>>         unsigned char temp; // in F
>>         unsigned int16_t depth; // in 1/16 ft
>>         unsigned int16_t deco : 1;
>>         unsigned int16_t tank_idx : 2;
>>         unsigned int16_t marker : 1;
>>         unsigned int16_t ascend_warn : 1;
>>         unsigned int16_t compass : 9;
>>         unsigned int16_t pressure; // in psi
>>         unsigned char flags;
>> }
>>
>> I made this up - it's much simpler than some real structures actually are.
>>
>> The goal is to allow me to say
>>
>> if (sample->deco) { ... }
>>
>> instead of
>>
>> if (data[3] & 0x01) { ... }
>>
>> and
>>
>> show_direction(sample.compass)
>>
>> instead of
>>
>> show_direction((array_16_le(data + 3) >> 5) & 0x1f)
>
>

<snip>

>
> There is also another alternative. When using structures as the in-memory
> representation, none of the above problems applies, as long as you fill in
> the contents of the struct using the portable method:
>
> sample->deco = data[3] & 0x01;
>
> and from there on, you can use your nice struct:
>
> if (sample->deco) { ... }
>

and this is how it should be done for clarity, if there are a lot of
actions with the read data.
then you do the reverse (CPU struct -> specific byte order) when exporting.

obviously for a very simple usage:
get_my_portable_value_le(x + offset)

is fine...

lubomir
--


More information about the subsurface mailing list