Roman Rdgz
Roman Rdgz

Reputation: 13254

Reading a buffer bitwise

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

I need to read it. It would be great if there where some library which allowed reading it using a pointer at bit level, and not a byte level.

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

Any idea?

EDIT: I will try to explain the magnitude of my problem with 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 copying to an struct, pragma pack, and go. But I have been told in previous questions that it is not a good solution, because of portability. But I am willing to hear a different opinion if it rescues me.

Upvotes: 4

Views: 2427

Answers (3)

Andriy
Andriy

Reputation: 8604

You can define a struct with bitfields:

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

This trick would work if the sum of lengths of all bitfields in the struct is a multiple of 8.

Upvotes: 0

Minion91
Minion91

Reputation: 1929

there are no real bitwise methods in C (in fact, it's even hard to come across an embedded platform that still supports these).

your best bet is using the bitwise operations << >> & and |.

Upvotes: 0

Denis Ermolin
Denis Ermolin

Reputation: 5546

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;
}

Upvotes: 3

Related Questions