bit manipulation - setting bits of a byte in C -
im try set bits of byte , based on function signature
int setbits(int old_value, int position, int width, int set_value)
what doing wrong, because 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) ( 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 - least significant bit of old_value wish change //old_value - value before start changing //width - width in bits of value want change (old_value width). //set_value - value want use modify 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; (c; c<width ; c++) { mask = mask << 1; } printf("ini mask %x \n",mask); //shift position set_value (aka state) mask = mask >> position; printf("shifted mask %x \n",mask); //if state 1 if (set_value) { return_val = mask | old_value; } else { return_val = (~mask) & old_value; } } else { printf("setbits(), position out of range, position : %x, width : %x", position, width); } return return_val; }
correcting code
int setbits(int old_value, int position, int width, int set_value) { int mask = 0x1; int return_val = 0x0; if ((0 < position) && (position <= width) ) { //initialize mask mask = mask << width; printf("ini mask 0x%02x \n",mask); //shift position set_value (aka state) mask = mask >> position; printf("shifted mask 0x%02x \n",mask); //if state 1 if (set_value) { return_val = mask | old_value; } else { return_val = (~mask) & old_value; } printf("returned value: 0x%02x\n", return_val); } else { printf("setbits(), position out of range, position : %x, width : %x", position, width); } return return_val; }
with example you'll output:
ini mask 0x10 shifted mask 0x04 returned value: 0x0a
that expected.
value --> 0x0a --> 0b00001010 mask --> 0x04 --> 0b00000100 ~mask --> 0xfb--> 0b11111011 value & ~mask = 0x0a
Comments
Post a Comment