0

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?

0decimal0
  • 3,884
  • 2
  • 24
  • 39

2 Answers2

3
  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))
    
DaoWen
  • 32,589
  • 6
  • 74
  • 101
  • +1 Oh!! that's wonderful, that seems to be working, thanks !! Its probably my lack of knowledge of proper methods. I beg pardon for another question out of topic ,actually I am new in java and there seem to be a flurry of methods and classes , How can one get hold of each? – 0decimal0 Aug 29 '13 at 05:50
  • 1
    @PHI - Reading other peoples' code helps. Just looking through the JavaDocs can help too. A lot of times you can just do a search like ["java find highest order bit"](https://www.google.com/search?q=java+find+highest+order+bit) and you'll find someone else already asked a similar question on stackoverflow and received some great answers! – DaoWen Aug 29 '13 at 05:58
0

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

1111111111111111111111111111111111111111110110010010111110101110 != 10110010010111110101110
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275