Print BinaryString without padding

73 views Asked by At

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

There are 2 answers

2
DaoWen On BEST ANSWER
  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))
    
0
Evgeniy Dorofeev On

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

1111111111111111111111111111111111111111110110010010111110101110 != 10110010010111110101110