1
#include <stdio.h>
int main()
{
    int num, i = 0,pos;
    printf(" Enter num \n");
    scanf("%d",&num);
    for( i = 0; i < 31; i++ )
    {   
        pos = 1 << i;

        if ( num & pos )
            printf("1");
        else
            printf("0");

    }   
    printf("\n");
    return 0;
}

/*
O/P
Enter Num
12
0011000000000000

*/

But i want to print the o/p as 0000000000001100 So, What are the changes i have to made to get the desired o/p

detly
  • 29,332
  • 18
  • 93
  • 152
user559208
  • 1,485
  • 3
  • 13
  • 9
  • By any chance were you just messing around with this question:http://stackoverflow.com/questions/4597940/how-to-insert-zeros-between-bits-in-a-bitmap - that's why I had a replacement `for` loop just lying around... – Michael Burr Jan 05 '11 at 05:44

3 Answers3

1

You're printing the least significant bit first. Change your for loop to count down:

      for (int i = 31; i >= 0; i--)
Daniel Gallagher
  • 6,915
  • 25
  • 31
0

EDIT: Seem that I'm the one who overlooked desired output. So the solutions provided by others will work for the OP.


I'm surprised people overlooked the fact that endianness usually applies to byte level instead of bit, which make the plain index-based loop fail to provide required output.

for a decimal to big-endian byte, you need :

while (num)
{
    big <<= 8;
    big |= num & 0xFF;
    num >>= 8;
}

so in order to output little-endian integer into big-endian binaries, you need :

// 'num' was 4-byte (int) data in little-endian format
while (num)
{
    // select required byte block
    unsigned char curByte = num & 0xFF;

    // prints the byte binaries
    for(int iBit=7; iBit>=0; --iBit)
    {
        unsigned char theBit = curByte >> iBit;
        if (theBit & 0x1)
            putchar('1');
        else
            putchar('0');

    }

    // shifts to next byte block
    num >>= 8;
}
YeenFei
  • 3,180
  • 18
  • 26
  • 1
    I'm pretty sure the OP simply wanted the binary representation of the int printed out in with most-significant bit on the left and least-significant on the left. Look at his example at the end of his question. – Michael Burr Jan 05 '11 at 06:18
-1

Change your for loop to be more like:

#define BIT(x) (1U << (x))

for (i = 31; i >= 0; --i)
{
    if (x & BIT(i)) {
        putchar('1');
    }
    else {
        putchar('0');
    }

}
Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • @YeenFei: I don't think the question was talking about byte-order endianness - just the bit order of his printout of the bits in an `int`. – Michael Burr Jan 05 '11 at 06:20