I have a key for a cipher in the form "XY XY+1 XY+2 XY+3 XY+4 XY+5 FF FF" where XY is an unknown byte, for example, XY could be 00000000 so XY+1 is 00000001. Also, FF is a constant so always 11111111.
l have an addBinary()
method which simply adds 1 to any binary string I give it, however, I'm finding it hard to generate all binary strings composing of "xxxx... 11111111 11111111".
I also found this printB()
method on StackOverflow which generates the strings but just not sure how to hard code the FF's into it.
static void printB()
{
for(int i = 0; i < Math.pow(2,8); i++)
{
String format="%0"+8+"d";
System.out.printf(format,Integer.valueOf(Integer.toBinaryString(i)));
System.out.println();
}
}
Any help on how to generate this strings would be appreciated
If you want to have the binary number to be prefixed with 0-s you have to do a bit of work. Here I used a StringBuilder filled with 0s, replacing from the end the binary representation without 0 padding.
for (int i = 0; i <= 0xFF; i++) {
StringBuilder builder = new StringBuilder("00000000");
String binary = Integer.toBinaryString(i);
builder.replace(8 - binary.length(), 8, binary);
System.out.println(builder);
}
I recommend not working with strings of "1"
and "0"
except for formatting output. Internally you should store your "key" as a byte[8]
, so:
byte[] key = new byte[8];
for(int i=0; i<6; i++) {
key[i] = (byte) x + i;
}
key[6] = (byte) 0xff;
key[7] = (byte) 0xff;
As a first shot at converting this to a printable string, you just need:
String result = IntStream.range(0,8)
.map(i -> key[i])
.mapToObj(n -> intToBinaryString(n))
.collect(Collectors.joining(" "));
... and then you need an intToBinaryString()
method. There are plenty of SO answers describing how to do this - for example: Print an integer in binary format in Java
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.