是否有一个printf转换器的二进制格式打印?

编程入门 行业动态 更新时间:2024-10-23 14:22:30
本文介绍了是否有一个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转换器的二进制格式打印?

本文发布于:2023-11-08 15:53:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569812.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换器   有一个   格式   printf

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!