简体   繁体   中英

Unary operator negation in C not working

I am trying to flip bits of a number using the unary operator ~ in C but the function seems to be returning nothing. The code i have made is as follows:

#include<stdio.h>
int flipBits(int n) {
    return ~n;
}
void convertbinary(int n)
{
    while(n>0)
    {
        printf("%d",n%2);
        n=n/2;
    }
}
int main()
{
    int n=21;
    int x=flipBits(n);
    convertbinary(x);
}

The output for the above code is nothing. It return -22. What i am trying to accomplish eventually is to change the MSB of a given number to 0. The solution i came up with was

n&&((n^~(n)>>1)

So, basically XOR-ing the number with its inverse to get all 1's and then right shifting to make the MSB 0 and AND-ing with the original number to make the MSB of the oriiginal number 0. For example

if n=21 i.e. 10101; ~n=01010; n^~n=11111; (n^~n)>>1 = 01111; n&&((n^~n)>>1)=00101

Please correct me if i am doing anything wrong. Thank you.

The code doesn't print anything because the negation of 21 is a negative number.

21 = 0000000...010101

Flipping every bit yields:

1111111...101010

So, the loop condition ( n > 0 ) is never true. You probably want while (n != 0) instead:

void convertbinary(int n)
{
    while (n != 0)
    {
        printf("%d",n%2);
        n=n/2;
    }
}

Or you can keep using n > 0 and make n an unsigned .

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