Bit not operation in PHP(or any other language probably)

前端 未结 4 1193
予麋鹿
予麋鹿 2021-01-21 17:50

Why does this code return -1 ?

$a = 0; 
echo ~$a;

Isn\'t not suppose to revert the bits ?

4条回答
  •  无人及你
    2021-01-21 18:21

    The integers are stored in 2's compliment form .

    this form can be outline ad follows :

    1) If the number to be stored is an positive value then its binary value is stored

    eg $val = 5 ;

    here $val contains ordiary binary equivlent of 5 = 0101 //number of bits depends on specifics

    2) if you are storing negative of an number say -5 , then the twos compliment s stored

    $val = -5;
    

    here first 2's compliment of 5 is found out ie, simply 1's compliment of 5 + 1

    ~ 0101 = 1010
    

    tnen add 1

      1010 + 
         1
      -----
      1011
    

    and this 1011 gets stored in $val .

    in same way , $val=0 ; 00 is stored

    ~$val => 11 which is the equalient of -2 in 2's compliment form

    and finally , if you observe carefully , you may ask ,

    so how could I represent 11 ? for its binary values is 1011 that clashes with -5's value in 2's comp ?

    the answer lies in number of bits used to represent number.

    in 2's complimwent form if there are n bits then you can represent only values from

    -2^(n-1) to 2^(n-1) -1 ;
    

提交回复
热议问题