Im try to set the bits of a byte , based on this function signature
int setbits(int old_value, int position, int width, int set_value)
what am I doing wrong, because it keeps returning 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;
}