Mike
Mike

Reputation: 963

Bit masking confusion

I get this result when I bitwise & -4227072 and 0x7fffff:

0b1111111000000000000000

These are the bit representations for the two values I'm &'ing:

-0b10000001000000000000000

0b11111111111111111111111

Shouldn't &'ing them together instead give this?

0b10000001000000000000000

Thanks.

Upvotes: 0

Views: 89

Answers (3)

5gon12eder
5gon12eder

Reputation: 25419

The negative number is represented as its 2's complement inside the computer's memory. The binary representation you have posted is thus misleading. In 2's complement, the most significant digit (at bit k) has value –2k–1. The remaining digits are positive as you expect.

Assuming you are dealing with 32 bit signed integers, we have:

   1111 1111 1011 1111 1000 0000 0000 0000  =  −422707210
 & 0000 0000 0111 1111 1111 1111 1111 1111  =    7fffff16
————————————————————————————————————————————————————————————
   0000 0000 0011 1111 1000 0000 0000 0000

Which is what you got.

To verify the first line:

−1 × 231  =  −214748364810
 1 × 230  =   107374182410
 1 × 229  =    53687091210
 1 × 228  =    26843545610
 1 × 227  =    13421772810
 1 × 226  =     6710886410
 1 × 225  =     3355443210
 1 × 224  =     1677721610
 1 × 223  =      838860810
 1 × 221  =      209715210
 1 × 220  =      104857610
 1 × 219  =       52428810
 1 × 218  =       26214410
 1 × 217  =       13107210
 1 × 216  =        6553610
 1 × 215  =        3276810
——————————————————————————————
                −422707210

Upvotes: 2

chux
chux

Reputation: 153468

0b10000001000000000000000 is correct - if your integer encoding was signed-magnitude.

This is possible on some early or novel machines. Another answer well explains how negative integers are typically represented as 2's complement numbers and then the result is as you observed: 0b1111111000000000000000.

Upvotes: 1

AlexD
AlexD

Reputation: 32576

-4227072 == 0xFFBF8000 == 1111 1111 1011 1111 1000 0000 0000

-4227072 & 0x7fffff should be

   0xFFBF8000 == 1111 1111 1011 1111 1000 0000 0000 0000
&    0x7fffff == 0000 0000 0111 1111 1111 1111 1111 1111
   -----------------------------------------------------
   0x003F8000 == 0000 0000 0011 1111 1000 0000 0000 0000

Upvotes: 4

Related Questions