C ++ Qt: bitwise operations

I am working on a small project for college, and I need to simulate the transmission over the network, as well as implement and visualize various error correction algorithms. My improvised package consists of one quint8: I need to convert it to a bit array, for example QBitArray, add a control bit to it, redirect it to UDP, check the transmission with the check bit and then build quint8 from it. Once again, this is not practical but an educational task, so don’t suggest me use real algorithms like CRC ...

So my question is: how to convert any data type (in this case quint8) to QBitArray? I mean that any data on the computer is a bit array, but how do I access the question.

Thank you Dmitry.

+3
source share
3 answers

Let's see if we can fix it correctly.

template < class T >
static QBitArray toQBit ( const T &obj ) {
    int const bitsInByte= 8;
    int const bytsInObject= sizeof(T);

    const quint8 *data = static_cast<const quint8*>(&obj) ;
    QBitArray result(bytsInObject*bitsInByte);
    for ( int byte=0; byte<bytsInObject ; ++byte ) {
        for ( int bit=0; bit<bitsInByte; ++bit ) {
            result.setBit ( byte*bitsInByte + bit, data[byte] & (1<<bit) ) ;
        }
    }
    return result;
}

void Foo () {
    Bar b ;
    QBitArray qb = toQBit ( b ) ;
}
+5
source

qint8 is actually a signed char. That way you can treat your objects as a char array.

template < class T >
QBitArray toQBit ( T &obj ) {
    int len = sizeof(obj) * 8 ;
    qint8 *data = (qint8*)(&obj) ;
    QBitArray result ;
    for ( int i=0; i< sizeof(data); ++i ) {
        for ( int j=0; j<8; ++j ) {
            result.setBit ( i*8 + j, data[i] & (1<<j) ) ;
        }
    }
    return result;
}

void Foo () {
    Bar b ;
    QBitArray qb = toQBit ( b ) ;
}
+1
source

, uint8. , unsigned long

#include <bitset>
template <typename T>
QBitArray toQBit(T val) {
    std::bitset<sizeof(T) * 8> bs(val);
    QBitArray result(bs.size());
    for (int ii = 0; ii < bs.size(); ++ii) {
        result.setBit(ii, bs.test(ii));
    }
    return result;
}

There is no way to generally convert any type of data into a bitmap. Especially if your data type contains pointers, you probably want to wrap the pointer, not the pointer. Therefore, any complex type should be considered separately. And keep abreast of the various endiannes (low-north and big-endian) in different architectures. I think std :: bitset is safe in accordance with this problem, but, for example, casting a pointer to a struct to a char array and storing its bits may be unsafe.

0
source

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


All Articles