我们展示了两个将单个字符打印为二进制的函数。
void printbinchar(char character)
{
char output[9];
itoa(character, output, 2);
printf("%s\n", output);
}
printbinchar(10) 将写入控制台
1010
itoa 是一个库函数,可将单个整数值转换为具有指定基数的字符串。
例如... itoa(1341, output, 10) 将写入输出字符串“1341”。
当然 itoa(9, output, 2) 会写入输出字符串“1001”。
下一个函数会将一个字符的完整二进制表示打印到标准输出中,也就是说,它将打印所有 8 位,如果高位为零。
void printbincharpad(char c)
{
for (int i = 7; i >= 0; --i)
{
putchar( (c & (1 << i)) ? '1' : '0' );
}
putchar('\n');
}
printbincharpad(10) 将写入控制台
00001010
现在我提出一个打印出整个字符串(没有最后一个空字符)的函数。
void printstringasbinary(char* s)
{
// A small 9 characters buffer we use to perform the conversion
char output[9];
// Until the first character pointed by s is not a null character
// that indicates end of string...
while (*s)
{
// Convert the first character of the string to binary using itoa.
// Characters in c are just 8 bit integers, at least, in noawdays computers.
itoa(*s, output, 2);
// print out our string and let's write a new line.
puts(output);
// we advance our string by one character,
// If our original string was "ABC" now we are pointing at "BC".
++s;
}
}
但请考虑 itoa 不添加填充零,因此 printstringasbinary("AB1") 将打印如下内容:
1000001
1000010
110001