How to parse n-bit elements from a byte address array

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

11110000 10101010 11001100 

at

an array for example

111100|001010|101011|001100

(may have zero padding, just need to address this path)

and the data is an 8-bit array, which is also a multiple of 6-bit and not infinite

+3
source share
6 answers

Depends on how many bits of a byte have in your particular architecture. In a six-bit architecture, this is quite simple :-)

Assuming 8 bits per byte architecture, you will have to do something line by line:

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
}

n - n- 6- . ands. , .

+8

5- , , ( ) , .

, ...

+1

, -:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    unsigned char source[3] = { 15, 85, 51 };
    unsigned char destination[4];
    memset(destination, 0, 4);
    for (int i = 0; i < (8 * 3); ++i)
    {
        destination[i / 6] |= ((source[i / 8] >> (i % 8) & 1) << (i % 6));
    }

    for (int j = 0; j < 4; ++j)
        printf("%d ", destination[j]);
}

:

15 20 53 12

, .

      15       85       51
11110000 10101010 11001100
111100 001010 101011 001100
    15     20     53     12

, :

destination[i / 6] |= ((source[i / 8] >> (7 - (i % 8))) & 1) << (5 - (i % 6));

, :

240      170      204
11110000 10101010 11001100
111100 001010 101011 001100
60     10     43     12
+1

:

struct bit5
{
    unsigned int v1 : 5;
    unsigned int v2 : 5;
    unsigned int v3 : 5;
    unsigned int v4 : 5;
    unsigned int v5 : 5;
    unsigned int v6 : 5;
    unsigned int v7 : 5;
    unsigned int v8 : 5;
}; 

struct bit5 8 ​​ (40 = 8 5 , 8 ), 5- . :

unsigned char* array; // a byte array that you want to convert
int i;
struct bit5* pBit5;

for(i = 0; i < (int)(SIZE_OF_ARRAY / 8); i++)
    pBit5 = (struct bit5*)((int)array + i * 8);
0

BitStream. . ( < lt; n). , 8- , , , .

0

?

union _EIGHT_TO_SIX_ {

    struct {

       unsigned char by6Bit0 : 6;
       unsigned char by6Bit1 : 6;
       unsigned char by6Bit2 : 6;
       unsigned char by6Bit3 : 6;

    } x6;

    struct {

       unsigned char by8Bit0;
       unsigned char by8Bit0;
       unsigned char by8Bit0;

    } x8;
}

by8Bitx 6Bitx ~~~

0

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


All Articles