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

Samuel Liu
3 min readOct 7, 2021

--

Description:

此function可以將某數某範圍的bits移到另一個範圍

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);
}

Explanation:

先用get_mask取出舊範圍的bits,再將他移到新的範圍變成set_mask,接著用erase_mask將新範圍的bits清除成0,最後再用set_mask將bits複製過去到新的範圍。

--

--