简体   繁体   中英

C Swapping with shifting bits

Here is a program to swap two numbers with out using temporary variable and using shifting operations:

#include <stdio.h>
#include <conio.h>
int main(void)
{
    int a,b,i,j;
    clrscr();
    printf(“Enter two integers: “);
    scanf(“%d%d”,&a,&b);
    printf(“a=%d,b=%d\n”,a,b);
    for(i = 0; i < 16; i++)
    {
        if((a & (1 << i)) ^ (b & (1 << i)))
        {
            a = a ^ (1 << i);
            b = b ^ (1 << i);
        }    
    }
    printf(“a=%d,b=%d”,a,b);
    getch();
    return 0;
}

My question is what is significance of 1 in this program? I know the method of xoring that works as follows

a = a^b;
b = a^b;
a = a^b;

but I don't know how above program works?

It toggles each bit if only one is set.

c = a & (1 << i) = true if the ith bit of a is set

d = b & (1 << i) = true if the ith bit of b is set

| c | d | Action          | c' | d' |
-------------------------------------
| 0 | 0 | Do nothing      | 0  | 0  |
| 0 | 1 | Toggle the bits | 1  | 0  |
| 1 | 0 | Toggle the bits | 0  | 1  |
| 1 | 1 | Do nothing      | 1  | 1  |

1 has one bit on the rightmost position set. 1<<i has one bit on place i set. This program loops through each bit, and swaps them if they are different.

  • a&(1<<i) tests if a has bit i set.
  • ((a&(1<<i))^(b&(1<<i))) tests if bit i in a and b are different.
  • a=a^(1<<i) toggles bit i .

It's similar to the XOR trick, but swaps only a single bit at a time and only if this bit actually differs in a and b .

1<<i has bit i set to 1 and all other bits 0.

Also, this does not swap two numbers without using a temporary variable . It uses the temporary i .

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