二进制按位赋值(对某位进行0或1赋值)与二进制打印输出

 说明:采用VS编译出现:The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant,请参考:VS编译出现‘itoa‘

#include <stdio.h>
#include <stdlib.h>
#define SIZE 5


/************************************************************************
功能: 二进制某位置零或者一
说明
* p_data:	需修改的值
position:	位数((从0 开始))
flag:		置零或一
/************************************************************************/
void Binary_Bit(unsigned char* p_data, unsigned char position, int flag)
{
	//二进制某位置零或者一 position为位数(从0 开始)
	if (flag)
	{
		*p_data |= 0x01 << (position);
	}
	else
	{
		*p_data &= ~(0x01 << (position));
	}
}


/************************************************************************
功能: 主函数
/************************************************************************/

void main(void)
{
	char num1 = 15;		//二进制为:1111
	char num2 = num1;
	char string[5] = { 0 };   //形参类型char最大为4位,因此我这里定义了大小为5的字符串数组存放
	_itoa(num1, string, 2);
	printf("num1 = %s\n",string);		//打印num1的二进制输出


	Binary_Bit(&num2,2,0); //对num2,二进制中的第2位置零
	_itoa(num2, string, 2);
	printf("num2 = %s\n", string);

	return 0;

}

输出值为:(num2中,第三位为零,从0开始计算为第二位)

num1 = 1111
num2 = 1011