Pergunta

I'm looking for a way to sbitshift a QByteArray.

QByteArray statusByte = QByteArray::fromHex("40");  // 0100 0000

What i need to achieve is to get statusByte to 0x20 by bit shifting. Since I can't directly bit shift the QByteArray, what is the simplest method for achieving the shift?

Foi útil?

Solução 2

Bit shifting is not a problem when you are talking about single byte, this is trivial (I don't know why you claim it is impossible).

QByteArray statusByte = QByteArray::fromHex("40");
statusByte[0] = statusByte[0]>>1;
statusByte[0]>>=1; // this should also work

if you have multiple bytes then it is more complicated!

  1. endian! How do you define shift where the oldest bit should go, to next byte or to previos byte?
  2. what should happen when array ends? loose data, or extend array?

Outras dicas

You don't really need a byte array if you only want to get a single numeric (byte) value from a hexadecimal representation of one byte, not multiple bytes.

#if 1
  // Qt 5, C++11 compilers
  quint8 byte = QStringLiteral("40").toInt(nullptr, 16);
#endif
#if 0
  // Qt 5, pre-C++11 compilers
  quint8 byte = QStringLiteral("40").toInt(NULL, 16);
#endif
#if 0
  // Qt 4
  quint8 byte = QByteArray("40").toInt(NULL, 16);
#endif
byte >>= 1;
Q_ASSERT(byte == 0x20); // this is for demonstration only

If you need to bit-shift multiple bytes at once, of course it's also possible - please amend your question to make that clear.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top