vendredi 14 juillet 2017

How implement random access iterator for sequence of element, which less 1 byte?

How implement random access iterator for sequence of element, which less 1 byte? For example 6 bits.

code example to illustrate what i want:

template<typename T>
class val_iterator : std::iterator<std::random_access_iterator_tag, T>
{
    // ???
};

template<typename T>
class val_container
{
    void *_data;
public:
    val_container(void *data): _data(data) {}
    // ???
};

int main()
{
    std::vector<unsigned int> vec =
    {
        0xA, // '00 1010'
        0xE, // '00 1110'
        0x1F,// '01 1111'
        0x3F // '11 1111'
    };

    // 4 elements of 6 bits
    const size_t byte_count = 4 * 6 / 8;

    std::array<unsigned char, byte_count> bytes;
    val_container<unsigned char> values(bytes.data());

    val_iterator<unsigned char> val_it = values.begin();
    for(auto it = vec.begin(); it != vec.end(); ++it, ++val_it)
        *val_it = (unsigned char) *it;

    // elements:
    // '00 1010'_'00 1110'_'01 1111'_'11 1111'
    // bytes in memory:
    // '0010 1000'_'1110 0111'_'1111 1111'
    assert(bytes[0] == 0x28);  // '0010 1000'
    assert(bytes[1] == 0xE7);  // '1110 0111'
    assert(bytes[1] == 0xFF);  // '1111 1111'

    assert(values[0] == 0xA);  // '00 1010'
    assert(values[1] == 0xE);  // '00 1110'
    assert(values[2] == 0x1F); // '01 1111'
    assert(values[3] == 0x3F); // '11 1111'
    return 0;
}

I also think that this byte sequence consists of repeating blocks of three bytes each, which store 4 elements each. Maybe it's like it can be used in an iterator, but I don't know how, yet.

Aucun commentaire:

Enregistrer un commentaire