Aventinus
Aventinus

Reputation: 1382

How can I add the missing bits to my binary values?

I'm generating random keys of k bits in binary and storing them in the keysArray.

public String[][] keysArray = new String[2][l];

// Method to generate random keys of k bits
public String keyGenerator(int k) {

        SecureRandom srandom = new SecureRandom();
        // Constructor: BigInteger(int numBits, Random rnd)
        // Create a random big integer of k bits using secure random
        BigInteger bg = new BigInteger(k, srandom);

        // Return the bg with radix 2 (= show it in binary)
        return bg.toString(2);

 }

 public void setKeysArray() {

        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < l; j++) {
                keysArray[i][j] = keyGenerator(k);
            }
        }
    }

I need the keys to always be of size k (i.e. 128). The thing is that some of the keys have size less of k which is perfectly expected due to the fact that their very left bits may be zeros.

111001001011101011101101101011110101111011010011001100010011010000101011000111100000111010000001001100100111101111011000010110
10110011100011110100010110111110001100101101010101111100110001111011011011111010110011100000010111110110101011100001000110110111
100111001000010100100011110110101100110000110011000010000011010010000001001101100100111001100011000000010111000101110001000101
10000100001101001110110111011000111010111101000001110010001000101100010110010010011111011010101011111101000100011100001011100011
1000111101010011111101010000011011000001001000010001111001011010110110110000000000110000110011110100111100110100010010111011
110000010101001100001101000100011001101000110011000101111000000010100001110110000011001101000001001001111000110000000011000001
11001010100110100010001101111100100001110011100001001011111010100011110101110100000011010111010110011111101010010001111010001110
1100100111101101100110101100000111111101000000110000110011001011010001110001101010101110111011100101100110000001110101011111111
11000011011011011101000110000011110001101010111111100010010000011011000010000111000001000100111011100010110010000110111001010001
1010111001010111011010000111110000001011101111100011111011101001101010000010101100110111101101010000111001011101101001000000001

What is the best way to add the missing bits to my keys?

Upvotes: 0

Views: 48

Answers (1)

Naruto
Naruto

Reputation: 4329

You can pad it with zero when it is less than 128 using String.format method

String.format("%0128d", num); 

Upvotes: 1

Related Questions