回复:(weishanhu03)在C语言中怎么把一个数转换成二...
/*---------------------------------------------------------------------------
File name: 二进制转换.c
Author: HJin (email: fish_sea_bird [at] yahoo [dot] com )
Created on: 8/24/2007 01:42:24
Environment: Windows XP Professional SP2 English +
Visual Studio 2005 v8.0.50727.762
Modification history:
===========================================================================
Problem statement:
---------------------------------------------------------------------------
http://bbs.bc-cn.net/viewthread.php?tid=164607
在C语言中怎么把一个数转换成二进制然后输出呢?
比如:
int a=12;
怎么把他以二进制的形式1100输出呢?
Sample output:
---------------------------------------------------------------------------
Please enter an integer:
0
0
There are 1 binary bits.
0
Please enter an integer:
1
1
There are 1 binary bits.
1
Please enter an integer:
12
1100
There are 4 binary bits.
1100
Please enter an integer:
31
11111
There are 5 binary bits.
11111
Please enter an integer:
2147483647
1111111111111111111111111111111
There are 31 binary bits.
1111111111111111111111111111111
Please enter an integer:
-1
11111111111111111111111111111111
There are 32 binary bits.
11111111111111111111111111111111
Please enter an integer:
-2
11111111111111111111111111111110
There are 32 binary bits.
11111111111111111111111111111110
Please enter an integer:
-2147483647
10000000000000000000000000000001
There are 32 binary bits.
10000000000000000000000000000001
Please enter an integer:
-2147483648
10000000000000000000000000000000
There are 32 binary bits.
10000000000000000000000000000000
Please enter an integer:
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
int numBits;
int t;
int i;
char s[50];
while(1)
{
puts("\nPlease enter an integer: ");
scanf("%d", &n);
// Option 1
// itoa --- note that
// itoa is NOT a standard C function.
itoa(n, s, 2);
puts(s);
// Option 2:
if(n>=0)
{
numBits=0;
t=n;
do
{
++numBits;
t>>=1;
}
while(t);
}
else
{
numBits=32;
}
printf("There are %d binary bits.\n", numBits);
for(i=numBits-1; i>=0; --i)
{
printf("%d", (n>>i)&1);
}
printf("\n");
}
return 0;
}