문제

Suppose I have defined a long variable like this :

    long lng = 2543697L;

and print it out :

    System.out.println (" first long "+Long.toBinaryString(lng));

the output is this :

1001101101000001010001

but when I complement the bits using ~ a lots of leading 1's appear :

1111111111111111111111111111111111111111110110010010111110101110

and that makes sense (padding). Now my questions are :

1. Why do these leading `1's appear in negation but not in original?

2. What should I do if I do not want to print them but just the complemented original bits only?

도움이 되었습니까?

해결책

  1. The 1's appear in the negated version because that's how the Two's Complement binary representation for negative numbers works: -x = ~x + 1
  2. If you want to limit the number of bits printed, I'd just count the number of bits used in the first number and only print that many bits from the second. Long.numberOfLeadingZeros could be helpful here:

    Long.toBinaryString(~lng).substring(Long.numberOfLeadingZeros(lng))
    

다른 팁

The leading 1s are significant, if you remove them you will change the number:

1111111111111111111111111111111111111111110110010010111110101110 != 10110010010111110101110
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top