Pregunta

I guess the output should be "0000" but it's ffff as Not of ~ffff->0000 0000 0000 0000

#include<stdio.h>
int main()
{
    unsigned int a=0xffff;
    ~a;
    printf("%x\n", a);
    return 0;
}
¿Fue útil?

Solución

As Tim and Vlad said, you aren't doing anything with the bit-wise inversion.

Even if you change the code to a = ~a;, you may not get zero. That's because if unsigned int has more than 16 bits, you'll have leading zeros, which become 1's after inversion.

So I expect your output to be

FFFF0000

or even

FFFFFFFFFFFF0000

If you want 16-bit bitwise operations, you can use

#include <inttypes.h>
uint16_t a;

Otros consejos

You need to assign the value back to a:

a = ~a;

Even then, the outputted value can look like this, due to the size of the datatype:

ffff0000

To make it work as expected (all 0s), set the initial value of a to UINT_MAX (from limits.h). Doing so sets all the bits to 1.

Writing ~a; has no effect. It's an expression which returns the complement of a, but doesn't change a itself.

You want a = ~a;.

Because you didn't assign the value to a. You need a = ~a;

~a by itself is a statement that returns the bitwise complement of a. You can either assign a to ~a (as @timcooper suggests), or you can

printf("%xn", ~a);

As others have already said, you need to either assign the value back into a with a = ~a; or print the result directly with printf("%x\n",~a); but in either case, you are still not going to get zero as you expect.

The ~ operator will flip all the bits in the variable. Since you are most likely dealing with 32-bit integers, you are going to end up with 0xFFFF0000 because those upper 16 bits will be flipped from zero's to one's.

#include<stdio.h>
int main()
{
    unsigned short int a= 0xffff;
    a=~a;
    printf("%x\n", a);
    return 0;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top