-2

Reading about binary operations in Java i'm stack of next example :

10111011 & 00001000 = 00001000

00001000 is a 8 in decimal represenation

but when i try to execute the following code :

    System.out.println("10111011 & 00001000 = " + (0b10111011 & 0b00001000));
    System.out.println("10111011 & 00001000 = " + Integer.toString(0b10111011 & 0b00001000, 2));

i getting output :

10111011 & 00001000 = 8 // right!
10111011 & 00001000 = 1000 // not a 00001000!

So i have 2 questions :

1) Why when i make conjunction operations i have invalid result?(My mistake)

2) Why in output i have only part visible of bits? How i can see all of bits count? Why Integer.toString(value,radix) doesn't return full record as 00001000?

Can be deleted. Problem solved. My mistake

Community
  • 1
  • 1
Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
  • 3
    1. Why were you expecting `4`? 2. Why would it show more bits than necessary; how many zeroes would you have liked?! – jonrsharpe Feb 25 '15 at 22:12
  • 1
    Anything without the `4` bit set for a bitwise and sure isn't going to have it set in the result. Because leading zeros aren't significant? You probably want to format it. – Dave Newton Feb 25 '15 at 22:12
  • @jonrsharpe 1) i added a link of online converter. 2) Just for fun. I use a http://stackoverflow.com/questions/2406432/converting-an-int-to-a-binary-string-representation-in-java to help of output. – Sergey Shustikov Feb 25 '15 at 22:14
  • That doesn't answer either of my questions. – jonrsharpe Feb 25 '15 at 22:14

1 Answers1

3

1) The result is correct 00001000 in binary = 8 in decimal. Why were you expecting 4? Even your question mentions the correct answer.

2) The toString method for int does not zero pad values.

iheanyi
  • 3,107
  • 2
  • 23
  • 22
  • how i can specify of output? – Sergey Shustikov Feb 25 '15 at 22:15
  • 1
    @SergeyShustikov See http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html You'd generally use String.Format(...) in this case. My original answer was slightly inaccurate as it suggested you could pass a format string to the toString method. – iheanyi Feb 25 '15 at 22:21