System.out.println(Integer.toBinaryString(2+24)); // 11010
This uses the Integer.toBinaryString
method. There's also toHexString
, toOctalString
, and a toString
with variable radix.
If you need the string to be zero-padded to a specific width, you can write something simple like this:
static String binaryPadded(int n, int width) {
String s = Integer.toBinaryString(n);
return "00000000000000000000000000000000"
.substring(0, width - s.length()) + s;
}
//...
System.out.println(binaryPadded(2+24, 8)); // 00011010
There are different ways to zero pad a string to a fixed width, but this will work for any int
value.
For hexadecimal or octal, you can use formatting string instead:
System.out.println(String.format("%04X", 255)); // 00FF
The specification isn't very clear, but it looks like you want this mapping:
0 -> 1
1 -> 2
2 -> 4
3 -> 8
4 -> 16
:
i -> 2
i
In that case, your mapping is from i
to (1 << i)
(the <<
is the bitwise left-shift operator).
System.out.println(
(1 << 2) + (1 << 4)
); // 20
Note that depending on what is it that you're trying to do, you may also consider using a java.util.BitSet
instead.
BitSet
demonstration
This may be completely off-the-mark, but assuming that you're doing some sort of interval arithmetics, then BitSet
may be the data structure for you (see also on ideone.com):
import java.util.BitSet;
//...
static String interval(BitSet bs) {
int i = bs.nextSetBit(0);
int j = bs.nextClearBit(i);
return String.format("%02d:00-%02d:00", i, j);
}
public static void main(String[] args) {
BitSet workTime = new BitSet();
workTime.set(9, 17);
System.out.println(interval(workTime));
// 09:00-17:00
BitSet stackOverflowTime = new BitSet();
stackOverflowTime.set(10, 20);
System.out.println(interval(stackOverflowTime));
// 10:00-20:00
BitSet busyTime = new BitSet();
busyTime.or(workTime);
busyTime.or(stackOverflowTime);
System.out.println(interval(busyTime));
// 09:00-20:00
}
Note that methods like nextSetBit
and nextClearBit
makes it easy to find empty/occupied time slots. You can also do intersect
, or
, and
, etc.
This simple example only finds the first interval, but you can make this more sophisticated and do various arithmetics on non-contiguous time intervals.