If I have understood correctly, you just need to prepend the correct number of zeroes to your binary string so there are 7 bits in all. The standard trick to generate a small fixed number of a character is to use String.substring()
on a constant string of that character. Since a char
fits in 16 bits, we will never need more than 16 zeroes:
String binaryString = Integer.toBinaryString(ch);
int missingZeroes = desiredNumberOfBits - binaryString.length();
if (missingZeroes > 0) {
binaryString = "0000000000000000".substring(0, missingZeroes) + binaryString;
}
System.out.println(binaryString);
If ch
is a char
holding a 1
, the above prints
0110001
You can fill in c[i] | d[i]
instead of ch
if that is what you require.
You may want to add a defensive check that the string from Integer.toBinaryString()
is not already too long.