View Full Version : QByteArray conversions/manipulation.... HOW TO DO IT?
daemonna
8th September 2010, 14:43
i got several questions regarding QByteArray conversion and manipulation...
1. how do i convert QByteArray to QBitArray and vice versa? following code should put bytearray to bitarray... is it OK? how it is other way? only change of operator <<?
QBitArray bita;
QByteArray byta;
QDataStream bytads(&byta, QIODevice::ReadWrite);
operator>>(bytads,bita);
2. how do I write/read bytearray from sharedmemory? following code should read 8 bytes form shared memory into bytearray... how to write it?
sharedmem.lock();
QByteArray memar=QByteArray((char*)sharedmem.constData(), 8);
sharedmem.unlock();
daemonna
8th September 2010, 15:32
just thought on conversion... can I do it this way?
QVariant(some_qbytearray).toBitArray
and
QVariant(some_qbitarray).toByteArray
tbscope
8th September 2010, 15:59
The main question is:
How do you convert
101011100101001001110
To an array of bytes?
Note that a bit array is something completely different than a byte array.
The bit array is mainly used for setting flags.
daemonna
8th September 2010, 17:46
Note that a bit array is something completely different than a byte array.
The bit array is mainly used for setting flags.
yes, but i got data from socket as bytearray...
with QByteArray.mid(x, 1) i will extract some byte and i need to change specific bits on that byte.
How to do that?
tbscope
8th September 2010, 18:00
Just use bitwise operators.
Either shift to the left or right, use AND, OR, XOR etc...
Example:
unsigned char byte1 = 4; // This is the binary number: 00000100
unsigned char byte2 = 2; // This is the binary number: 00000010
usigned char byte1and2 = byte1 & byte2; // This is the binary number: 00000000
usigned char byte1or2 = byte1 | byte2; // This is the binary number: 000001100
etc...
wysota
8th September 2010, 18:00
with QByteArray.mid(x, 1) i will extract some byte and i need to change specific bits on that byte.
How to do that?
You don't need QBitArray for that. Just access the data you need and set respective bits using regular C/C++ bit operators. Transforming QByteArray to QBitArray and then back would just give you needless overhead.
MTK358
8th September 2010, 21:48
To set a bit:
byte |= 1 << bitnum
To clear a bit:
byte &= ~(1 << bitnum)
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.