5

I am writing a method where I am converting int values into binary strings and storing them. I am using the method Integer.toBinaryString to do so, and it's working correctly, but the problem is that I need the method to return exactly 4 bits in the string instead of less (it will never be more because the numbers are not large enough). Here is an example of my code and where the problem is occurring:

int value5 = 3;
String strValue5 = Integer.toBinaryString(value5);
for(int index = 0; index < 4; index++){
     sBoxPostPass[4][index] = strVal5.charAt(index);
}

Clearly, this will throw an ArrayOutOfBoundsException because strValue5 == 11 and not 0011, like it needs to be. I hope this is sufficiently clear. Thanks in advance for the help.

4

3 回答 3

4

A trick to return at least 4 digits is have a 5 digit number and chop off the first digit.

String strValue5 = Integer.toBinaryString(value5 + 0b10000).substring(1);
于 2012-08-04T08:13:17.733 回答
2

I'm not guaranteeing this is the most efficient method, but you can always make your own method that calls Integer.toBinaryString and formats it appropriately:

public static String toBinaryStringOfLength(int value, int length) {
    String binaryString = Integer.toBinaryString(value); 
    StringBuilder leadingZeroes = new StringBuilder();
    for(int index = 0; index < length - binaryString.length(); index++) {
        leadingZeroes = leadingZeroes.append("0");
    }

    return leadingZeroes + binaryString;
}

Keep in mind I didn't account for the situation in which the value you're sending requires more bits to represent in binary than the length that you provide.

于 2012-08-03T23:44:57.837 回答
1

If your value will always have exactly 4 bits then that's small enough to use a look-up table for the 16 values in question. Correcting any errors in my Java is left as an exercise for the reader.

static String binary4[16] = {"0000", /* another exercise for the reader */, "1111"};
static String toBinary4(int value) {
    return binary4[value & 0xF];
}
于 2012-08-03T23:38:52.867 回答