How to force Integer.toBinaryString to return at least 4 bits

I am writing a method in which I convert int values ​​to binary strings and store them. I use the Integer.toBinaryString method for this, and it works correctly, but the problem is that I need a method that returns exactly 4 bits per line, and not less (this will never be more, because the numbers are not big enough). Here is an example of my code and where the problem occurs:

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

Obviously, this will throw an ArrayOutOfBoundsException because strValue5 == 11, and not 0011, as it should be. Hope this is clear enough. Thank you in advance.

+5
source share
3 answers

4 , , 16 , . Java .

static String binary4[16] = {"0000", /* another exercise for the reader */, "1111"};
static String toBinary4(int value) {
    return binary4[value & 0xF];
}
+1

4 5- .

String strValue5 = Integer.toBinaryString(value5 + 0b10000).substring(1);
+4

, , , Integer.toBinaryString :

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;
}

, , , , .

+2

All Articles