Saturday, May 7, 2016

Bit Operations: Qt Example

In this post i'm going to show you some bit operations with &, |, <<, >>, ~ using Qt example. This example include operations like set a particular bit in the given number, clear bit, check bit is set or not and to check whether the number is even or odd.

Following demonstrates the psuedo code of the operations.

> To Set a bit in the given number : perform Betwise OR (|) operation with  1 left shift(<<) by index of the bit to set
     num = num | (1<<index);

>To clear a bit in the given number: perform Betwise AND (&) operation with the inverted(~) 1 left shift(<<) by index of the bit to clear
    num = num & ~(1<<index);

>To Check whether a bit is set or not: perform Betwise AND (&) operation between num right shift(>>) by index of the bit to check and 1
num = (num >> index) & 1;

>To Check whether a num is even or odd:  perform Betwise AND (&) operation with  1. If it returns 1 number is odd, if returns 0 even number
bool ret = (num & 1);

And the following code demonstrates the sample Qt application example for the above operations.


#include <QCoreApplication>
#include<QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    quint8 testByte = 8;

    qDebug()<<"test byte: "<<testByte;

    //set bit at 2nd index
    testByte = testByte | (1<<2);
    qDebug()<<"After set bit at 2nd index: "<<testByte;

    //clear bit at 3rd index
    testByte = testByte & ~(1<<3);
    qDebug()<<"After clear bit at 3rd index: "<<testByte;

    //check bit at 2nd index
    bool isBitChecked = (testByte>>2) & 1;
    qDebug()<<"check bit at 2nd index: "<<isBitChecked;

    //to find the number is even or odd
    qint32 num = 3;
    QString evenOdd = (num & 1)? "Odd":"Even";
    qDebug()<<"num 3 is : "<<evenOdd;

    return a.exec();
}

output:
test byte: 8
After set bit at 2nd index: 12
After clear bit at 3rd index: 4
check bit at 2nd index: true
num 3 is : "odd"




1 comment: