PDA

View Full Version : how to set different bits of a byte



saman_artorious
26th February 2013, 16:36
I never faced this case to change the bits of one byte. My variable were always bytes, so I always used
QByteArray to append every hex to it. Now, in the new case, Some variables are one byte, but some other
variable are only bits, that is I need to set each bit of one byte. I am looking for a nice way to implement this in Qt.
what do you suggest?

Ashkan_s
26th February 2013, 16:57
Take a look at QBitArray

ChrisW67
26th February 2013, 21:51
Manipulating bits in bytes/ints etc. is generic C/C++, not something you need Qt for. It is done with the bitwise OR (|), AND (&) and XOR (^) operators:


unsigned char byte;
byte = 0; // set all the bits
byte |= 1; // set LSB (bit 0)
byte |= 128 ; // set MSB (bit 7)
byte |= 1 << 2 ; // set bit 2
byte |= 8 | 16; // set some more bits

byte &= ~4; // unset bit 2
byte &= ~(8 | 16); // unset some more bits

byte ^= 64; // toggle bit 6
byte ^= 64; // toggle bit 6 back again

wysota
26th February 2013, 22:28
I'm wondering if it is safe to use bitfields for this...

ChrisW67
26th February 2013, 22:57
Cannot say I know the standard well enough to know the actual allocated size of a bitfield structure and any bit ordering stipulations; it does seem the entire concept is compiler dependent though. I do know that a bitfield that will not fit in the existing allocation will cause another int (or whetever) to be allocated and a bit gap inserted.