I'm trying to do a simple caesarian shift on a binary string, and it needs to be reversable. I've done this with this method..
public static String cShift(String ptxt, int addFactor)
{
String ascii = "";
for (int i = 0; i < ptxt.length(); i+=8)
{
int character = Integer.parseInt(ptxt.substring(i, i+8), 2);
byte sum = (byte) (character + addFactor);
ascii += (char)sum;
}
String returnToBinary = convertToBinary(ascii);
return returnToBinary;
}
This works fine in some cases. However, I think when it rolls over being representable by one byte it's irreversable. On the test string "test!22*F "
, with an addFactor
of 12
, the string becomes irreversible. Why is that and how can I stop it?
edit: For clarification sake, the test string is converted to binary before being passed in. Here is convertToBinary
public static String convertToBinary(String str)
{
char [] array = str.toCharArray();
String binaryToBeReturned = "";
for (int i = 0; i < str.length(); i++)
{
String binary = Integer.toBinaryString((int)array[i]);
binary = padZeroes(binary);
binaryToBeReturned += binary;
}
return binaryToBeReturned;
}
When I run this with a cShift of 12, followed by a cShift of -12 to reverse, I get this...
01110100011001010111001101110100001000010011001000110010010001100010101000100000
111111111000000001110001011111111111111110000000001011010011111000111110010100100011011000101100
ÿ?qÿ?->>R6,
ÿótesÿót!22F*
The first string is just converting the test string to binary. The second string is the result of the cShift in binary. The third string is the result of converting this to ascii, and the fourth string is the result of reversing with -12 on cShift and converting to ascii.
It's pretty clear to me that somehow there are extra bits being added from the roll over and I'm not totally sure how to deal with it. Thanks.