Dillydill123 - 1 month ago 10x

C++ Question

in c++, I have the following code:

`int x = -3;`

x &= 0xffff;

cout << x;

This produces

`65533`

But if I remove the negative, so I have this:

`int x = 3;`

x &= 0xffff;

cout << x;

I simply get

`3`

Why does the first result not produce a negative number? I would expect that -3 would be sign extended to 16 bits, which should still give a twos complement negative number, considering all those extended bits would be 1. Consequently the most significant bit would be 1 too.

Answer

It looks like your system uses 32-bit `int`

s with two's complement representation of negatives.

Constant `0xFFFF`

covers the least significant two bytes, with the upper two bytes are zero.

The value of `-3`

is `0xFFFFFFFD`

, so masking it with `0x0000FFFF`

you get `0x0000FFFD`

, or `65533`

in decimal.

Positive `3`

is `0x00000003`

, so masking with `0x0000FFFF`

gives you `3`

back.

You would get the result that you expect if you specify 16-bit data type, e.g.

```
int16_t x = -3;
x &= 0xffff;
cout << x;
```

Source (Stackoverflow)

Comments