The purpose of this lab is to give students practice with bitwise operators and loops in Java by implementing a program that converts an
int into a
String that holds the 1s and 0s that make it up in binary. Your final solution must only use bitwise operators:
- Allowed: Binary AND (&), Binary OR (|), Binary XOR (^), Left Binary Shift (< <), and Unsigned Right Binary Shift (> > >)
- NOT Allowed: +, -, /, *, %
You should write a method which takes in an int and returns its binary representation. Since an int is 32 bits, the string should contain 32 characters. For instance, should yield 00000000000000000000000001111111 . Of course, you should come up with your own examples to check to make sure it's working.
Recall that you can concatenate two strings together with the
+operation in Java. So
"1" + "001"is
"1001". The one place you're allowed to use + in your code is with strings
To extract the rightmost bit, you can write
This works, because
1is 00000000000000000000000000000001, so taking a binary AND with it will zero everything out except for the rightmost bit. If the rightmost bit is 0, the result will be 0, and if the rightmost bit is 1, the result will be 1.
- To get bits other than the first bit, try using one of the shift operators to help you.
Java's Built-In Converter
If you want to have something to check against to save you time, you can compare the output of your method to Java's implementation. I've provided a method below you can use which also takes in an int and returns a string to the specifications.
What To Submit
You must submit the file
Lab8.java to Canvas.