# Bits manipulating question

• Hi to all!

I've been writing some app that communicates with some device via modbus. Now, the communication works fine, but the device returns me data of type short and its structure is as follows:
bits 0-11: specific service code
bits 12-13: router status
bit 14: unused, always set to 0
bit 15: command response flag

How do get this bits in most elegant way, QBitArray conversion from short simply does not work! I've tried to use C++ bitfields but Ido not know how to query bits!

Sincerely,
Marko

EDIT: moved to C++ as it's a general C++ problem

• you can query bits by shifting and masking:

@
short myBitField = 0x0F37;

``````// check one bit by masking
bool bitSet = myBitField & 0x0020;

// check bit 4 bit by shift and masking
bool bitSet = (myBitField > 3) & 0x0001;
``````

@

• Ok, but how do I get bits 0-11 from my scheme?

• make a bit mask:

@
// bit mask for bits 0 - 11
short bitMask = 0x07FF;

``````short myBitField = 0x0F37;

// check one bit by masking
short bitSet = myBitField & bitMask;
``````

@

• You create a mask that covers all those bits. If you want to make it easier to write the masks, perhaps "Boost::binary":http://www.boost.org/doc/libs/1_42_0/libs/utility/utility.htm#BOOST_BINARY can help you.

• if you're stuck with bitsets, an easy way is :

• define a bunch of macro constants, defining value for each bit
#define BIT0 1
#define BIT1 2
#define BIT2 4
...
(note that bitX constant = 2 power x)
• to create the mask, use binary "or" : mask = BIT0 | BIT3 | BIT 4
• to compare, use binary and (&) : check if (bitset & mask) != 0

E.g. : 17 = 2^4 + 2^0 => bit 0 and bit4 set, all other unset
check bit 0 :
(17 & BIT0) = (17 & 1) = 1 != 0 <<<< bit 0 is set

check bit 3 :
(17 & BIT3) = (17 & 8) = 0 == 0 <<<< bit 3 not set

• To control bits, you can use:

• | (binary or ) => sets bit
• & with negative mask => unset bit
• not that negative mask can be done using ~ (binary inversion) : result = result & (~BIT4) <<< unsets bit 4