简体   繁体   English

如何更改下一位的位置?(仅使用位操作)

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

for example 10'00'11'01'01 -> 01'00'11'10'10例如 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.从我看来,您似乎需要一个函数来交换数字中每 2 位的位置。 few examples:几个例子:

  1. 10'00'11'01'01 -> 01'00'11'10'10 10'00'11'01'01 -> 01'00'11'10'10
  2. 11'01'10'10'11 -> 11'10'01'01'11 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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