Search This Blog

Saturday, December 19, 2009

Function to check number of bits set in a number

/* Untested! */
int total_bit_set(int number)
{
#define MAX_BIT_NUM 32 /* test for 32bit numbers */
#define MASK 0x01

int i = 0;
int total = 0;
for (i=0; i < MAX_BIT_NUM; ++i)
{
total = ( number & MASK ) ? total+1 : total ;

/* Right shift by 1 bit */
number = (number >> 1);
}

return total;
}

Saturday, August 1, 2009

IS_POWER_OF_TWO macro

Power of two numbers means that 2 multiplied by itself multiple times to produce another number (power of two numbers). 1 is also power of two numbers when 2 is multiplied to itself 0 time (zeroth power of 2 - don't ask me why :P).

Check if a number is power of two using macro defined function:

#define IS_POWER_OF_TWO(x) ( !( (x) & ((x)-1) ) )

e.g.
i. 4 is power of 2 (2x2)
4 == 0000 0100 binary
4-1 = 3 == 0000 0011 binary
ANDED == 0000 0000
! == 1111 1111 == is a power of two

ii. 8 is power of 2 (2x2x2)
8 == 0000 1000 binary
8-1 = 7 == 0000 0100 binary
ANDED == 0000 0000
! == 1111 1111 == is a power of two

iii. 15 is NOT power of 2 ( 2x2x2 == 8, 2x2x2x2 == 16 which already passed 15)

15 == 0000 1111 binary
15-1 = 14 == 0000 1110 binary
ANDED == 0000 1110 ( ! will result 0 )
! == 0000 0000 == not a power of two number

e.g C codes
#include
#include

#define ISPOW2(x)
!((x)&((x-1)))

int main (int argc, char *argv[])
{
int i=0;
int res=0;

if ( argc < face="courier new" size="2">
{

printf("Not enough input arguments\n");


return -1;

}

i = atoi(argv[1]);

if ( (res=ISPOW2(i)) )
printf("Number %d is a power of 2.\n", i);

else

printf("Number %d is NOT a power of 2.\n", i);

printf ("res = %d\n", res);

return 0;
}


De Morgans laws

To simplify if else statement / understand advanced programmers codes...

1. !(a && b) == (!a || !b)
2. !(a || b) == (!a && !b)

Friday, July 31, 2009

Yet another blog

Hahaha... yet another blog in blogspot created...
What the heck is this blog for? I don't know....
Let us all see what will happen ...