8

可能重复:
是否有 printf 转换器以二进制格式打印?

还在学习 C,我想知道:

给定一个数字,是否可以执行以下操作?

char a = 5;
printf("binary representation of a = %b",a);
> 101

还是我必须编写自己的方法来转换为二进制?

4

8 回答 8

29

没有直接的方法(即使用printf或其他标准库函数)来打印它。您将不得不编写自己的函数。

/* This code has an obvious bug and another non-obvious one :) */
void printbits(unsigned char v) {
   for (; v; v >>= 1) putchar('0' + (v & 1));
}

如果您使用的是终端,则可以使用控制代码以自然顺序打印出字节:

void printbits(unsigned char v) {
    printf("%*s", (int)ceil(log2(v)) + 1, ""); 
    for (; v; v >>= 1) printf("\x1b[2D%c",'0' + (v & 1));
}
于 2009-03-31T04:21:10.790 回答
26

基于dirkgently 的回答,但修复了他的两个错误,并始终打印固定数量的数字:

void printbits(unsigned char v) {
  int i; // for C89 compatability
  for(i = 7; i >= 0; i--) putchar('0' + ((v >> i) & 1));
}
于 2009-03-31T06:01:37.087 回答
14

是的(自己写),类似于下面的完整函数。

#include <stdio.h> /* only needed for the printf() in main(). */
#include <string.h>

/* Create a string of binary digits based on the input value.
   Input:
       val:  value to convert.
       buff: buffer to write to must be >= sz+1 chars.
       sz:   size of buffer.
   Returns address of string or NULL if not enough space provided.
*/
static char *binrep (unsigned int val, char *buff, int sz) {
    char *pbuff = buff;

    /* Must be able to store one character at least. */
    if (sz < 1) return NULL;

    /* Special case for zero to ensure some output. */
    if (val == 0) {
        *pbuff++ = '0';
        *pbuff = '\0';
        return buff;
    }

    /* Work from the end of the buffer back. */
    pbuff += sz;
    *pbuff-- = '\0';

    /* For each bit (going backwards) store character. */
    while (val != 0) {
        if (sz-- == 0) return NULL;
        *pbuff-- = ((val & 1) == 1) ? '1' : '0';

        /* Get next bit. */
        val >>= 1;
    }
    return pbuff+1;
}

将此 main 添加到它的末尾以查看它的运行情况:

#define SZ 32
int main(int argc, char *argv[]) {
    int i;
    int n;
    char buff[SZ+1];

    /* Process all arguments, outputting their binary. */
    for (i = 1; i < argc; i++) {
        n = atoi (argv[i]);
        printf("[%3d] %9d -> %s (from '%s')\n", i, n,
            binrep(n,buff,SZ), argv[i]);
    }

    return 0;
}

运行它"progname 0 7 12 52 123"以获得:

[  1]         0 -> 0 (from '0')
[  2]         7 -> 111 (from '7')
[  3]        12 -> 1100 (from '12')
[  4]        52 -> 110100 (from '52')
[  5]       123 -> 1111011 (from '123')
于 2009-03-31T04:44:14.883 回答
6
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
void displayBinary(int n)
{
       char bistr[1000];
       itoa(n,bistr,2);       //2 means binary u can convert n upto base 36
       printf("%s",bistr);

}

int main()
{
    int n;
    cin>>n;
    displayBinary(n);
    getch();
    return 0;
}
于 2010-09-10T17:11:37.293 回答
4

使用查找表,例如:

char *table[16] = {"0000", "0001", .... "1111"};

然后像这样打印每个半字节

printf("%s%s", table[a / 0x10], table[a % 0x10]);

当然,您可以只使用一张桌子,但它会稍微快一些并且太大。

于 2009-03-31T04:52:16.503 回答
3

在 C 语言中没有直接的格式说明符。尽管我编写了这个快速的 Python 代码片段来帮助您逐步了解自己的流程。

#!/usr/bin/python

dec = input("Enter a decimal number to convert: ")
base = 2
solution = ""

while dec >= base:
    solution = str(dec%base) + solution
    dec = dec/base
if dec > 0:
    solution = str(dec) + solution

print solution

解释:

dec = input("输入要转换的十进制数:") - 提示用户输入数字(例如,在 C 中通过 scanf 有多种方法可以做到这一点)

base = 2 - 指定我们的基数为 2(二进制)

solution = "" - 创建一个空字符串,我们将在其中连接我们的解决方案

while dec >= base: - 当我们的数字大于输入的基数时

解决方案 = str(dec%base) + 解决方案- 获取数字的模数,并将其添加到字符串的开头(我们必须使用除法和余数方法从右到左添加数字)。str() 函数将运算结果转换为字符串。在没有类型转换的情况下,您不能在 python 中将整数与字符串连接起来。

dec = dec/base - 将十进制数除以基数以准备下一个模数

如果 dec > 0: solution = str(dec) + solution - 如果有任何剩余,请将其添加到开头(如果有的话,这将是 1)

打印解决方案 - 打印最终数字

于 2009-03-31T04:43:55.977 回答
3

此代码应能处理您最多 64 位的需求。



char* pBinFill(long int x,char *so, char fillChar); // version with fill
char* pBin(long int x, char *so);                    // version without fill
#define width 64

char* pBin(long int x,char *so)
{
 char s[width+1];
 int    i=width;
 s[i--]=0x00;   // terminate string
 do
 { // fill in array from right to left
  s[i--]=(x & 1) ? '1':'0';  // determine bit
  x>>=1;  // shift right 1 bit
 } while( x > 0);
 i++;   // point to last valid character
 sprintf(so,"%s",s+i); // stick it in the temp string string
 return so;
}

char* pBinFill(long int x,char *so, char fillChar)
{ // fill in array from right to left
 char s[width+1];
 int    i=width;
 s[i--]=0x00;   // terminate string
 do
 {
  s[i--]=(x & 1) ? '1':'0';
  x>>=1;  // shift right 1 bit
 } while( x > 0);
 while(i>=0) s[i--]=fillChar;    // fill with fillChar 
 sprintf(so,"%s",s);
 return so;
}

void test()
{
 char so[width+1]; // working buffer for pBin
 long int   val=1;
 do
 {
   printf("%ld =\t\t%#lx =\t\t0b%s\n",val,val,pBinFill(val,so,0));
   val*=11; // generate test data
 } while (val < 100000000);
}

Output:
00000001 = 0x000001 =   0b00000000000000000000000000000001
00000011 = 0x00000b =   0b00000000000000000000000000001011
00000121 = 0x000079 =   0b00000000000000000000000001111001
00001331 = 0x000533 =   0b00000000000000000000010100110011
00014641 = 0x003931 =   0b00000000000000000011100100110001
00161051 = 0x02751b =   0b00000000000000100111010100011011
01771561 = 0x1b0829 =   0b00000000000110110000100000101001
19487171 = 0x12959c3 =  0b00000001001010010101100111000011
于 2009-04-01T07:24:34.320 回答
2

您必须编写自己的转换。格式说明符仅支持十进制、十六进制和八进制数。

于 2009-03-31T04:20:34.940 回答