c语言关于二进制的输出

c语言中的二进制输出是没有占位符的,不像八进制:%o; 和十六进制:x%;

c中二进制的输出

 1 //右移31位,从最高为开始和1做&运算,得到每一位的二进制数值
 2 void printbinry(int num)
 3 {
 4     int count = (sizeof(num)<<3)-1;//值为31
 5     while (count>=0) {
 6         int bitnum = num>>count; //除去符号位,从最高位开始得到每一位
 7         int byte = bitnum & 1; //和1进行与运算得到每一位的二进制数
 8         printf("%d",byte);
 9         
10         if (count%4==0) {//每隔四位打印空格
11             printf(" ");
12         }
13         
14         count--;
15     }
16     printf("
");
17     
18 }

上边这种输出是不会改变符号的,即正负号不会改变,且代码简洁;

还有一种是用c语言自带的itoa函数,在头文件<stdlib.h>中

itoa(int value, char *str, int radix); 参数分别表示:
value:要转换的数字;
str:是一个字符串,存储转换后的进制;
radix:要转换的进制

 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 int main()
 4 {
 5     
 6     int a = 10;
 7     char str[100];
 8     itoa(a,str,2);
 9     
10     printf("%s
", str);
11     
12     return 0;
13 }

但是这种方式在xcode编译器环境下报一个链接错误:clang: error: linker command failed with exit code 1 (use -v to see invocation)

还不知道解决办法,求高人指点;

原文地址:https://www.cnblogs.com/cxbblog/p/3704825.html