我可以用printf打印十六进制或八进制数字。是否有格式标签打印为二进制或任意基数?
我正在运行gcc。
printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
printf("%b\n", 10); // prints "%b\n"
我可以用printf打印十六进制或八进制数字。是否有格式标签打印为二进制或任意基数?
我正在运行gcc。
printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
printf("%b\n", 10); // prints "%b\n"
当前回答
const char* byte_to_binary(int x)
{
static char b[sizeof(int)*8+1] = {0};
int y;
long long z;
for (z = 1LL<<sizeof(int)*8-1, y = 0; z > 0; z >>= 1, y++) {
b[y] = (((x & z) == z) ? '1' : '0');
}
b[y] = 0;
return b;
}
其他回答
我喜欢的代码由paniq,静态缓冲区是一个好主意。但是,如果你想在一个printf()中有多个二进制格式,它就失败了,因为它总是返回相同的指针并覆盖数组。
下面是一个C风格的下拉列表,它可以在分割缓冲区上旋转指针。
char *
format_binary(unsigned int x)
{
#define MAXLEN 8 // width of output format
#define MAXCNT 4 // count per printf statement
static char fmtbuf[(MAXLEN+1)*MAXCNT];
static int count = 0;
char *b;
count = count % MAXCNT + 1;
b = &fmtbuf[(MAXLEN+1)*count];
b[MAXLEN] = '\0';
for (int z = 0; z < MAXLEN; z++) { b[MAXLEN-1-z] = ((x>>z) & 0x1) ? '1' : '0'; }
return b;
}
C标准库中没有这样输出二进制的格式化函数。printf家族支持的所有格式操作都是针对人类可读的文本。
下面的函数返回给定无符号整数的二进制表示形式,使用不带前导零的指针算术:
const char* toBinaryString(unsigned long num)
{
static char buffer[CHAR_BIT*sizeof(num)+1];
char* pBuffer = &buffer[sizeof(buffer)-1];
do *--pBuffer = '0' + (num & 1);
while (num >>= 1);
return pBuffer;
}
注意,不需要显式设置NUL结束符,因为buffer表示一个具有静态存储持续时间的对象,该对象已经被全0填充。
通过简单地修改num形式参数的类型,可以很容易地将其适应为无符号long long(或另一个无符号整数)。
CHAR_BIT要求包含<limits.h>。
下面是一个用法示例:
int main(void)
{
printf(">>>%20s<<<\n", toBinaryString(1));
printf(">>>%-20s<<<\n", toBinaryString(254));
return 0;
}
其期望输出为:
>>> 1<<<
>>>11111110 <<<
const char* byte_to_binary(int x)
{
static char b[sizeof(int)*8+1] = {0};
int y;
long long z;
for (z = 1LL<<sizeof(int)*8-1, y = 0; z > 0; z >>= 1, y++) {
b[y] = (((x & z) == z) ? '1' : '0');
}
b[y] = 0;
return b;
}
接下来将向您展示内存布局:
#include <limits>
#include <iostream>
#include <string>
using namespace std;
template<class T> string binary_text(T dec, string byte_separator = " ") {
char* pch = (char*)&dec;
string res;
for (int i = 0; i < sizeof(T); i++) {
for (int j = 1; j < 8; j++) {
res.append(pch[i] & 1 ? "1" : "0");
pch[i] /= 2;
}
res.append(byte_separator);
}
return res;
}
int main() {
cout << binary_text(5) << endl;
cout << binary_text(.1) << endl;
return 0;
}