16 bit binary leading zeros
I am using toBinaryString translation method like this:
for (i=0; i<anyLines.length; i++) {
if (anyLines[i].startsWith("@")) {
anyLines[i] = anyLines[i].replace("@","");
anyLines[i] = Integer.toBinaryString((Integer.parseInt(anyLines[i])));
}
else {
continue;
开发者_C百科 }
But when I write to a file, the binary is only 2 bits long, though I want a 16 bit binary with all the zeros. For example, 2 is translated as 10, though I'd like to have 0000000000000010. How can I do that?
Just add 2^17 and substring
the whole string:
anyLines[i] = Integer.toBinaryString(131072 + (Integer.parseInt(anyLines[i]))).substring(1, 17);
After you set the binary string just check the string length and append enough zeros to the front of the string to make it 16 chars long.
精彩评论