0
林尝试设置一个字节的位,在此基础上函数签名设置位
int setbits(int old_value, int position, int width, int set_value)
什么我做错了,因为它使返回0。
#include "stdafx.h"
int setbits(int old_value, int position, int width, int set_value);
int _tmain(int argc, _TCHAR* argv[])
{
//for example turn hex 0xA (10 base 2) into (8 base 2)
int old_value = 0xA;
int position = 2;
int width = 4;
int set_value = 0;
printf("setbits, old_value %x, position %i, width %i, set_value %x, output %x",old_value,7,width,set_value,0);
getchar();
}
//position - is the least significant bit of the old_value you wish to change
//old_value - is the value before you start changing it
//width - is the width in bits of the value you want to change (old_value width).
//set_value - is the value you want to use to modify the bits
int setbits(int old_value, int position, int width, int set_value)
{
int mask = 0x1;
int return_val = 0x0;
if (0 < position <= width)
{
//initialize mask
int c=0;
for (c; c<width ; c++)
{
mask = mask << 1;
}
printf("ini mask %x \n",mask);
//shift into position the set_value (aka state)
mask = mask >> position;
printf("shifted mask %x \n",mask);
//if state is 1
if (set_value)
{
return_val = mask | old_value;
}
else
{
return_val = (~mask) & old_value;
}
}
else
{
printf("setbits(), position is out of range, position : %x, width : %x", position, width);
}
return return_val;
}
的[您如何设置,清除可能的复制并在C/C++中切换一个位?](http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-cc) –
也,如果(0 <位置<=宽度)错误。它应该是'if((0 <位置)&&(位置<=宽度))'。 –