bits manipulation
Hi all
I used this code to switch bit4 with bit0
1 2 3 4
|
a0=a & 0x01;
a4=a & 0x10;
aa=a & 0xEE;
e=aa |(a0<<4)|(a4>>4);
|
it is ok but a kind of long if i want to switch more bits! I believe that there is an easier way of doing it
any help !!!
thanks alot
Nope. That's the shortest possible.
It can be made more generic, though:
1 2 3 4 5 6 7
|
unsigned swapBits(unsigned x,unsigned bita,unsigned bitb){
//bita is assumend to be <=bitb
unsigned maska=1<<bita,
maskb=1<<bitb,
maskx=~(maska|maskb);
return ((x&maska)<<(bitb-bita))|((x&maskb)>>(bitb-bita))|(x&maskx);
}
|
Topic archived. No new replies allowed.