(声明:此为原创,首发于http://blog.csdn.net,转载请注明 “作者:究竟实相,邮箱:LmjLmj8@163.com”。本文所给代码可未经本人允许而做任何使用,但是本人不承担因此造成的任何后果)
在C语言程序中,可以使用标准库函数中printf()来向屏幕输出信息,或者使用sprintf()向缓冲区输出信息。对整数而言,可以使用%d、%o、%x(或%X)输出十进制形式、八进制、十六进制形式,但貌似缺乏二进制形式,这不得不说是一种遗憾。因此,网上经常见到有人询问如何解决这个问题,解决方式有两种,一种是利用Windows提供的itoa()函数,另一种自行设计一个新的函数。笔者昨晚测试一个新的想法时,恰好遇到这个问题,因此就提供了一种自创实现方法,与大家共享。为了对比,也给出了itoa()的实现。所有代码在Visual Studio 2013 Express测试通过。由于编辑器出了问题,无法将用中文来表示代码注释,请原谅。限于笔者水平有限,这里给出的代码可能还有一些不足,请大家指正。
/** Test.h */
#pragma once
#ifndef Test_H
#define Test_H
/** use itoa() to print integers in the form of binary
* @param[in] n the integer to print
* @return void
*/
void printBinaryByItoa(unsigned int n);
/** my function to print integers in the form of binary
* @param[in] n the integer to print
* @param[in] separator the separator to group binary bits. Each group has four bits. The common separators are ',' and ' '. If no need, set it 0
* @param[in] needPrefixZeros if true (any nonzero value), then prefix zeros will be printed out, else not
* @return void
*/
void printBinary(unsigned int n, unsigned char separator, unsigned char needPrefixZeros);
#endif //end of Test_H
/** Test.c */
#include <stdio.h>
#include <stdlib.h>
void printBinaryByItoa(unsigned int n)
{
unsigned char data[33];
_itoa_s(n, data, 33, 2);
printf("%sb\n", data);
}
void printBinary(unsigned int n, unsigned char separator, unsigned char needPrefixZeros)
{
unsigned int i = 0;
unsigned int mask = 0; /* the mask code to get each bit of n */
unsigned char data[40]; /* the buffer to store the bits of n in the form of characters */
unsigned int index = 0; /* used to access data[] */
unsigned int st