c语言一个数转换二进制输出,在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

#include

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值