Dillydill123
Dillydill123

Reputation: 693

Why does masking a negative number produce a positive number?

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 as a result

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.

Upvotes: 3

Views: 3179

Answers (2)

Alex Paniutin
Alex Paniutin

Reputation: 144

In your case int is more than 2 bytes. You probably run on modern CPU where usually these days integer is 4 bytes (or 32 bits)

If you take a look the way system stores negative numbers you will see that its a complementary number. And if you take only last 2 bytes as your mask is 0xFFFF then you will get only a part of it.

your 2 options:

  1. use short intstead of int. Usually its a half of integer and will be only 2 bites
  2. use bigger mask like 0xFFFFFFFF that it covers all the bits of your integer

NOTE: I use "usually" because the amount of bits in your int and short depends on your CPU and compiler.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726609

It looks like your system uses 32-bit ints 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;

Upvotes: 5

Related Questions