rawatadit
rawatadit

Reputation: 31

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.

Upvotes: 1

Views: 215

Answers (1)

Filipe Gon&#231;alves
Filipe Gon&#231;alves

Reputation: 21213

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.

Upvotes: 1

Related Questions