C语言中以二进制形式输出整数

本文介绍在C语言中如何以二进制形式输出整数,包括使用itoa()函数和自定义函数两种方法。代码已在Visual Studio 2013 Express测试通过,提供了多种打印选项,如是否添加前导零和分隔符。
摘要由CSDN通过智能技术生成

(声明:此为原创,首发于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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值