Lab 8: Binary Strings
Due Monday 3/30/2020
Overview
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: +, -, /, *, %
Code
You should write a method
1 2 3 | public static String getIntBitString( int x) { ... } |
1 | System.out.println(getIntBitString(127)); |
Hints
-
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, because1
int
bit = (x & 1);
1
is 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.
1 2 3 4 5 6 7 8 | /** * Convert an into a string representing its bits * @param x A 32-bit int * @return A 32-element binary string corresponding to this int */ public static String getIntBitStringJava( int x) { return String.format( "%32s" , Integer.toBinaryString(x)).replace( ' ' , '0' ); } |
What To Submit
You must submit the file Lab8.java
to Canvas.