Read buffer bitwise

I have a buffer with some data that have different bit sizes (field 8 bits, then field 4 bits, then field 9 bits ...).

I need to read this. It would be great if there was some kind of library that allowed you to read it using a pointer at the bit level rather than the byte level.

Copying the buffer into the structure is not an option, because after researching I will need to use #pragma pack() or something similar and will not be portable.

Any idea?

EDIT: I will try to explain the scale of my problem using an example:

 field1: 8 bits --> ok, get first byte field2: 6 bits --> ok, second byte, and a mask field3: 4 bits --> gets harder, i have to get 2 bytes, apply 2 different masks, and compose field4 ... field 15: 9 bits ---> No idea of how to do it with a loop to avoid writing manually every single case 

And the only solution I can think of is to copy to struct, pragma pack and go. But in previous questions I was told that this is not a good solution due to portability. But I am ready to hear a different opinion if it saves me.

+4
source share
3 answers

Use bit manipulation:

 unsigned char[64] byte_data; size_t pos = 3; //any byte int value = 0; int i = 0; int bits_to_read = 9; while (bits_to_read) { if (i > 8) { ++readPos; i = 0; } value |= byte_data[pos] & ( 255 >> (7-i) ); ++i; --bits_to_read; } 
+3
source

there are no real bitwise methods in C (in fact, it’s even hard to find an embedded platform that still supports them).

your best bet is to use bitwise operations << >> & and | .

0
source

You can define a structure with bit fields:

 struct Data { unsigned field1:8; unsigned field2:6; unsigned field3:4; // etc }; 

This trick will work if the sum of the lengths of all bit fields in the structure is a multiple of 8.

-1
source

Source: https://habr.com/ru/post/1441831/


All Articles