c语言关于二进制的输出

时间:2023-03-08 18:45:56

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

c中二进制的输出

 //右移31位,从最高为开始和1做&运算,得到每一位的二进制数值
void printbinry(int num)
{
int count = (sizeof(num)<<)-;//值为31
while (count>=) {
int bitnum = num>>count; //除去符号位,从最高位开始得到每一位
int byte = bitnum & ; //和1进行与运算得到每一位的二进制数
printf("%d",byte); if (count%==) {//每隔四位打印空格
printf(" ");
} count--;
}
printf("\n"); }

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

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

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

 #include <stdlib.h>
#include <stdio.h>
int main()
{ int a = ;
char str[];
itoa(a,str,); printf("%s\n", str); return ;
}

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

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