简体   繁体   中英

How to change place of the next bits?(use only bit operations)

for example 10'00'11'01'01 -> 01'00'11'10'10

void main() {
  unsigned int num = 78;
  unsigned int num2 = change_bit(num);
  printf("%d\n", num2); //141
}

I need a function like that.

From what I see, it seems that you need a function that swaps position of every 2 bits in a number. few examples:

  1. 10'00'11'01'01 -> 01'00'11'10'10
  2. 11'01'10'10'11 -> 11'10'01'01'11

for this operation, a very simple function is following:

unsigned int change_bit(unsigned int num)
{
    return ((num & 0xAAAAAAAA) >> 1) | ((num & 0x55555555) << 1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM