Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse out n-bit elements from a byte addressable array

I have a data stream that is addressable only in 8-bit bytes, I want to parse it out into 6-bit elements and store that into an array. Is there any best known methods to do this?

11110000 10101010 11001100 

into

an array like

111100|001010|101011|001100

(can have zero padding, just needs to be addressable this way)

and the data is an 8-bit array that is also a multiple of 6-bits , not really endless

like image 747
stbtra Avatar asked Dec 29 '22 08:12

stbtra


2 Answers

Depends how much bits a byte has on your particular architecture. On a six bit architecture it is quite simple :-)

Assuming a 8 bits per byte architecture you will have to do something along the lines:

int sixbits(unsigned char* datastream, unsigned int n) {
    int bitpos = n*6;
    return (datastream[bitpos/8] >> bitpos%8)    // lower part of the five bit group
        + (datastream[bitpos/8+1] << 8-bitpos%8) // if bitpos%8>2, we need to add some carry bits from the next char
        & 0x3f;                                  // and finally mask the lowest 6 bits
}

Where n is the n-th 6 bit group. Any decent compiler will substitute the division with shifts and the moduli with ands. Just use this function in a loop to fill up your destination array.

like image 122
Gunther Piez Avatar answered Jan 12 '23 00:01

Gunther Piez


You count your 5 bit sequences, read each byte, shift the bits based on your counter and the expected word position (by xor-ing pieces from neighboring byte words), and form new correctly aligned byte words that you then process.

I hope you don't expect code ...

like image 37
cdonner Avatar answered Jan 11 '23 23:01

cdonner