-7

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.

amdixon
  • 3,814
  • 8
  • 25
  • 34
  • are you using c or c++ ? – amdixon Nov 09 '15 at 08:03
  • I'm using C.But I know that bit operation is the same as in C as in C++. – V.Paprotsky Nov 09 '15 at 08:08
  • You can do it using an XOR temporary. But, depending on your requirements, and assembler solution might be the way to go here. See http://graphics.stanford.edu/~seander/bithacks.html#SwappingBitsXOR. – Bathsheba Nov 09 '15 at 08:09
  • 4
    Possible duplicate of [What are bitwise shift (bit-shift) operators and how do they work?](http://stackoverflow.com/questions/141525/what-are-bitwise-shift-bit-shift-operators-and-how-do-they-work) – 101010 Nov 09 '15 at 08:09
  • Use the >> bitwise operator. See here: http://www.tutorialspoint.com/cprogramming/c_bitwise_operators.htm – bpgeck Nov 09 '15 at 08:10
  • 1
    It is not really clear by your example what the function is supposed to do. Also you should make more clear wether you are using C or C++, they may look the same at first glance, but they are fundamentaly different! – NobbZ Nov 09 '15 at 08:10

1 Answers1

1

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);
}
Afshin
  • 8,839
  • 1
  • 18
  • 53