1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

How to print bit-patterns of a given integer

Discussion in 'C' started by heavensgate15, Apr 8, 2008.

  1. heavensgate15

    heavensgate15 New Member

    Joined:
    Mar 18, 2008
    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    Ei guyz, plss help on how to print bit-patterns of a given integer..

    Ex:

    given:
    x = 3;

    the output should look like this:

    0000000000000011


    _________________________________________________________________


    :eek: :eek: :eek:
     
  2. sherma20

    sherma20 New Member

    Joined:
    May 31, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    you can simply use a recursive function like this:

    void intTobinary(int num){

    if(num>0){
    intTobinary(num/2);
    printf("%d",num%2);
    }


    }


    of course you know you will need to make adjustments so that it prints the number of bit patterns that you want. eg. my code will print 11 when 3 is inputted, but you seem to want some zeroes in front of there...
     
  3. wesley001

    wesley001 New Member

    Joined:
    Jun 27, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Like this:
    Code:
    void int_to_binary(int x)
    {
    	int cnt, mask = 1 << 31;
    	
    	for(cnt=1;cnt<=32;++cnt)
    	{
    		putchar(((x & mask) == 0) ? '0' : '1');
    		x <<= 1;
    		if(cnt % 8 == 0 && cnt !=32)
    			putchar(' ');
    		if(cnt == 32)
    			putchar('\n');
    	}
    }
    
    ?:)
     

Share This Page