本文介绍了是否有一个printf转换器的二进制格式打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以用printf的为十六进制或八进制数字打印。有没有一种格式标签打印为二进制,或任意基地?
我正在运行的gcc。
的printf(%D%X%Ø\\ n,10,10,10); //输出10一个12 \\ n打印(%B \\ N,10); //输出%B \\ N解决方案
下面是一个快速的黑客演示技巧做你想做的。
的#include<&stdio.h中GT; / * * printf的/#包括LT&;&string.h中GT; / * *的strcat /#包括LT&;&stdlib.h中GT; / * *与strtol /为const char * byte_to_binary(INT X){ 静态炭B〔9〕; B [0] ='\\ 0'; INT Z者除外; 对于(Z = 128; Z大于0; Z>> = 1) { 的strcat(二((X安培; Z)== z)的1:0); } 返回b;}INT主要(无效){ { / *二进制字符串为int * / 字符* tmp目录; 字符* B =0101; 的printf(%d个\\ N,与strtol(B,&安培; TMP,2)); } { / *字节的二进制字符串* / 的printf(%S \\ n,byte_to_binary(5)); } 返回0;}I can print with printf as a hex or octal number. Is there a format tag to print as binary, or arbitrary base?
I am running gcc.
printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n" print("%b\n", 10); // prints "%b\n"解决方案
Here is a quick hack to demonstrate techniques to do what you want.
#include <stdio.h> /* printf */ #include <string.h> /* strcat */ #include <stdlib.h> /* strtol */ const char *byte_to_binary(int x) { static char b[9]; b[0] = '\0'; int z; for (z = 128; z > 0; z >>= 1) { strcat(b, ((x & z) == z) ? "1" : "0"); } return b; } int main(void) { { /* binary string to int */ char *tmp; char *b = "0101"; printf("%d\n", strtol(b, &tmp, 2)); } { /* byte to binary string */ printf("%s\n", byte_to_binary(5)); } return 0; }
更多推荐
是否有一个printf转换器的二进制格式打印?
发布评论