Saturday, December 17, 2011

Set or Clear Bits

Check whether kth bit is set or not .After that set/clear kth bit
Conditionally clear or set bits without branching

Set N bits in a number where N is a variable.

Solution:
// Display Every bits in a int number 
void displayBits(int data)
{
    int dataSize = 1<<sizeof(data);
    int count = 0;
    for (count = dataSize;count >= 0; count--)
    {
        printf("%d",(testBit(data,count)));
    }
}
// test a bit if it is zero or one 
int8_t testBit(int8_t value,int whichBit)
{
    int mask = 1 << whichBit;
    if (value&mask)
    {
        return TRUE;
    }
    else return FALSE;
}

// Set a bit to one 
int8_t setBit(int8_t result, int whichBit)
{
    return (result |= (1<<whichBit));
}

// toggle a bit  
int8_t toggleBit(int8_t result, int whichBit)
{
    return (result ^= (1<<whichBit));
}

/* Clear a bit to zero */
int8_t clearBit(int8_t result, int whichBit)
{
    return (result &=~ (1<<whichBit));
}

Useful Links:-
http://graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranching



3 comments:

  1. bool f;
    unsigned int m; // the bit mask
    unsigned int w; // the word to modify:if (f) w |= m; else w &= ~m;

    w ^= (-f ^ w) & m;

    ReplyDelete
  2. if n & (1 <<(k-1)) is true then kth bit is set

    n | (1<<(k-1)) will set the kth bit

    n & ~(1 << (k-1)) will clear kth bit

    ReplyDelete
  3. Set k lower order bits---

    if( k > 0 ) {
    x |= (0xffffffffu >> (32-k))
    }

    ReplyDelete