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?

2
  • 2
    They were leading zeroes in the original, so they didn't have to be printed. Commented Aug 29, 2013 at 5:38
  • @harold oops !! well , obviously that makes sense :). Commented Aug 29, 2013 at 5:52

2 Answers 2

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))
    
Sign up to request clarification or add additional context in comments.

2 Comments

+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?
@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" and you'll find someone else already asked a similar question on stackoverflow and received some great answers!
0

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

1111111111111111111111111111111111111111110110010010111110101110 != 10110010010111110101110

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.