python小菜 2008-09-21 20:04 采纳率: 0%
浏览 1395

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

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"

转载于:https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format

  • 写回答

30条回答 默认 最新

  • elliott.david 2011-01-29 21:34
    关注

    Here's a version of the function that does not suffer from reentrancy issues or limits on the size/type of the argument:

    #define FMT_BUF_SIZE (CHAR_BIT*sizeof(uintmax_t)+1)
    char *binary_fmt(uintmax_t x, char buf[static FMT_BUF_SIZE])
    {
        char *s = buf + FMT_BUF_SIZE;
        *--s = 0;
        if (!x) *--s = '0';
        for(; x; x/=2) *--s = '0' + x%2;
        return s;
    }
    

    Note that this code would work just as well for any base between 2 and 10 if you just replace the 2's by the desired base. Usage is:

    char tmp[FMT_BUF_SIZE];
    printf("%s\n", binary_fmt(x, tmp));
    

    Where x is any integral expression.

    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发