Domanda

Ho una grande mole di dati binari in un array char [] che devo interpretare come un array di valori compressi a 6 bit.

Io potrei sedermi e scrivere un po 'di codice per farlo, ma sto pensando che ci deve essere una buona classe esistente o una funzione che qualcuno ha già scritto.

Ciò di cui ho bisogno è qualcosa del tipo:

int get_bits(char* data, unsigned bitOffset, unsigned numBits);

in modo da poter ottenere il 7 ° carattere a 6 bit nei dati chiamando:

const unsigned BITSIZE = 6;
char ch = static_cast<char>(get_bits(data, 7 * BITSIZE, BITSIZE));
È stato utile?

Soluzione

Questo potrebbe non funzionare per dimensioni superiori a 8, a seconda del sistema endian. Fondamentalmente è quello che ha pubblicato Marco, anche se non sono del tutto sicuro del perché si raccolga un po 'alla volta.

int get_bits(char* data, unsigned int bitOffset, unsigned int numBits) {
    numBits = pow(2,numBits) - 1; //this will only work up to 32 bits, of course
    data += bitOffset/8;
    bitOffset %= 8;
    return (*((int*)data) >> bitOffset) & numBits;  //little endian
    //return (flip(data[0]) >> bitOffset) & numBits; //big endian
}

//flips from big to little or vice versa
int flip(int x) {
    char temp, *t = (char*)&x;
    temp = t[0];
    t[0] = t[3];
    t[3] = temp;
    temp = t[1];
    t[1] = t[2];
    t[2] = temp;
    return x;
}

Altri suggerimenti

Penso che qualcosa nella riga seguente potrebbe funzionare.

int get_bit(char *data, unsigned bitoffset) // returns the n-th bit
{
    int c = (int)(data[bitoffset >> 3]); // X>>3 is X/8
    int bitmask = 1 << (bitoffset & 7);  // X&7 is X%8
    return ((c & bitmask)!=0) ? 1 : 0;
}

int get_bits(char* data, unsigned bitOffset, unsigned numBits)
{
    int bits = 0;
    for (int currentbit = bitOffset; currentbit < bitOffset + numBits; currentbit++)
    {
        bits = bits << 1;
        bits = bits | get_bit(data, currentbit);
    }
    return bits;
}

Non ho eseguito il debug né testato, ma è possibile utilizzarlo come punto di partenza.

Inoltre, prendere in considerazione l'ordine dei bit. Potresti voler cambiare

    int bitmask = 1 << (bitoffset & 7);  // X&7 is X%8

a

    int bitmask = 1 << (7 - (bitoffset & 7));  // X&7 is X%8

a seconda di come è stato generato l'array di bit.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top