[C] Move a range of bits to a new range in a number

void move_bits(int *a, int l, int new_l, int num){
if(num == 0)
return;
//create get_mask
int get_mask = 0;
int count = num;
//create get mask
while(count){
get_mask = (get_mask << 1) + 1;
count--;
}
//cover get_mask on a and move to target range and become set_mask
get_mask = get_mask << l;
int set_mask = get_mask & (*a);
if(l > new_l)
set_mask = set_mask >> l - new_l;
else
set_mask = set_mask << new_l - l;
//create erase mask
int erase_mask = 0;
count = num;
while(count){
erase_mask = (erase_mask << 1) + 1;
count--;
}
erase_mask = ~(erase_mask << new_l);
//cover erase mask to a to erase 1234 bits to 0
*a = erase_mask & (*a);
//cover set_mask to a
*a = set_mask | (*a);
}
void move_bits(int *a, int *b, int l, int new_l, int num){
if(num == 0)
return;
//create get_mask
int get_mask = 0;
int count = num;
//create get mask
while(count){
get_mask = (get_mask << 1) + 1;
count--;
}
//cover get_mask on a and move to target range
get_mask = get_mask << l;
int set_mask = get_mask & (*a);
if(l > new_l)
set_mask = set_mask >> l - new_l;
else
set_mask = set_mask << new_l - l;
//create erase mask
int erase_mask = 0;
count = num;
while(count){
erase_mask = (erase_mask << 1) + 1;
count--;
}
erase_mask = ~(erase_mask << new_l);
//cover erase mask to a to erase 1234 bits to 0
*b = erase_mask & (*b);
printf("%x %x\n", erase_mask, set_mask);
//cover set_mask to a
*b = set_mask | (*b);
}

--

--

Hi I am Samuel

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store