输出一个整型数据的二进制形式(高效)

作者在 2009-04-12 11:30:09 发布以下内容

一般人会考虑用位运算,程序代码如下:

#include<stdio.h>

void Print(int n)
{
if(n==1||n==0)
{
   printf("%d",n);
   return;
}
Print(n>>1);
printf("%d",n%2);
}

int main()
{
int a;
scanf("%d",&a);
Print(a);
return 0;
}

我们现在用一种特别的方法.用位段,可以不用进行运算即可输出结果,首先我们用一个程序输出整型数据在内存中的形式,程序代码如下:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
unsigned char bit_1 : 1;
unsigned char bit_2 : 1;
unsigned char bit_3 : 1;
unsigned char bit_4 : 1;
unsigned char bit_5 : 1;
unsigned char bit_6 : 1;
unsigned char bit_7 : 1;
unsigned char bit_8 : 1;
}bit;

int main()
{
int *p_int=NULL, len=sizeof(int);
bit *p_bit=(bit *)malloc(len*sizeof(bit));
p_int=(int *)p_bit;
*p_int=0;
printf("Please input a int value! \n");
scanf("%d",p_int);
while(len--)//从高位到低位依次输出
printf("%d%d%d%d%d%d%d%d   ", (p_bit+len)->bit_1, (p_bit+len)->bit_2,
(p_bit+len)->bit_3, (p_bit+len)->bit_4,
(p_bit+len)->bit_5, (p_bit+len)->bit_6,
(p_bit+len)->bit_7, (p_bit+len)->bit_8) ;
printf("\n");
free(p_bit);
return 0;
}

如果要输出一个整型数据的二进制形式,对于小端的编译器,上面的即可,而大端编译器则需要将输出的顺序1-8颠倒一下即可.下面是适合大端的编译器.(VC++ 6.0是大端编译器)

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
unsigned char bit_1 : 1;
unsigned char bit_2 : 1;
unsigned char bit_3 : 1;
unsigned char bit_4 : 1;
unsigned char bit_5 : 1;
unsigned char bit_6 : 1;
unsigned char bit_7 : 1;
unsigned char bit_8 : 1;
}bit;

int main()
{
int *p_int=NULL, len=sizeof(int);
bit *p_bit=(bit *)malloc(len*sizeof(bit));
p_int=(int *)p_bit;
*p_int=0;
printf("Please input a int value! \n");
scanf("%d",p_int);
while(len--)
printf("%d%d%d%d%d%d%d%d   ", (p_bit+len)->bit_8, (p_bit+len)->bit_7,
(p_bit+len)->bit_6, (p_bit+len)->bit_5,
(p_bit+len)->bit_4, (p_bit+len)->bit_3,
(p_bit+len)->bit_2, (p_bit+len)->bit_1) ;
printf("\n");
free(p_bit);
return 0;
}

原创 | 阅读 3667 次
文章评论,共0条
游客请输入验证码
浏览194774次