I am getting the output in Big Endian Format
#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
You're printing the least significant bit first. Change your for loop to count down:
for (int i = 31; i >= 0; i--)
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;
}
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');
}
}
精彩评论