Here's a simple solution for int values; It should be obvious how to expand it to, for example, bytes, etc.
public static String bitString(int i, int len) { len = Math.min(32, Math.max(len, 1)); char[] cs = new char[len]; for (int j = len - 1, b = 1; 0 <= j; --j, b <<= 1) { cs[j] = ((i & b) == 0) ? '0' : '1'; } return new String(cs); }
Here is the result from a set of test cases:
0 1 0 0 0 -1 0 0 0 40 00000000000000000000000000000000 00000000000000000000000000000000 13 1 1 1 13 2 01 01 13 3 101 101 13 4 1101 1101 13 5 01101 01101 -13 1 1 1 -13 2 11 11 -13 3 011 011 -13 4 0011 0011 -13 5 10011 10011 -13 -1 1 1 -13 40 11111111111111111111111111110011 11111111111111111111111111110011
Of course, you yourself can make the length parameter sufficient to represent the entire value.
joel.neely
source share