Thursday, October 4, 2012

Bitwise Operators and Byte to Bit Conversion

# include "stdio.h"
# include "string.h"

const char* byte_to_binary( int x );
int main()
{

    int nInput=0, nOutput=2, nBitPos;

    // To set the bit in particular position.
    nInput |= (1 << nOutput);
    printf("To set the %d Position from 1bit of %s\n",nOutput, byte_to_binary(nInput));

    // To Reset/Clear the bit in particular position.
    nInput &= ~(1 << nOutput);
    printf("To Reset/Clear the %d Position from 1bit of %s\n",nOutput, byte_to_binary(nInput));

    // To toggle the bit in particular position.
    nInput =5; // 00000101 expected like 00000001
    nInput ^= (1 << nOutput);
    printf("To toggle the %d Position from 1bit of %s\n",nOutput, byte_to_binary(nInput));

    // To state of the bit in particular position.
    nInput =5; // 00000101 expected like 00000101
    nBitPos = nInput &(1 << nOutput);
    printf("To state of the %d Position from 1bit of %s:: state of bit: %d\n",nOutput, byte_to_binary(nInput), nBitPos);


return 0;
}



//To Byte to Binary Conversion
const char* byte_to_binary( int x )
{
    static char b[9] = {0};
    int z, y;

    for (z=128,y=0; z>0; z>>=1,y++)
    {
        b[y] = ( ((x & z) == z) ? '1' : '0');
    }

    b[y] = 0;

    return b;
}



Output:
To set the 2 Position from 1bit of 00000100
To Reset/Clear the 2 Position from 1bit of 00000000
To toggle the 2 Position from 1bit of 00000001
To state of the 2 Position from 1bit of 00000101:: state of bit: 4

No comments:

Post a Comment