-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

4
  • 3
    1. Why were you expecting 4? 2. Why would it show more bits than necessary; how many zeroes would you have liked?! Commented Feb 25, 2015 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. Commented Feb 25, 2015 at 22:12
  • @jonrsharpe 1) i added a link of online converter. 2) Just for fun. I use a stackoverflow.com/questions/2406432/… to help of output. Commented Feb 25, 2015 at 22:14
  • That doesn't answer either of my questions. Commented Feb 25, 2015 at 22:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

how i can specify of output?
@SergeyShustikov See 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.

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.