Good day,
I'm attempting to write a short encryption program. One stage of the encryption / decryption process will be bitshifting. However, this process ( using << and >> operators ) causes data corruption : the end bit is lost. I wish to make sure that, whether the bit added when the program is run, is a 0 or a 1, that my code will work. Therefore, I have put together the following program :
THEORY :
Encryption
Left bitshift by 1 bit. Endbit is lost. If endbit ( left bit representing 128 ) is 1, the value of character is bigger than 127. Therefore, if this is the case, bitshift 1 left, and then OR the value with the integer 1 ( 00000001 ) to wrap this bit on the end. This will correct the bitshift, whether the added bit on the right is a 1 or a 0.
If the value of the character is less than 128, then bitshift left, and check if this new value is odd. If it is, take away 1, else, do nothing. This will correct the value of the bitshifted char, whether the added bit was 1 or 0.
Decryption
Right bitshift by 1 bit. Endbit ( right bit representing 1 ) is lost. If the value of the character is odd, then the endbit = 1. In this case, bitshift right, and check if the new value is larger than 127. If so, the added bit was 1, so do nothing. If it is less than 128, add 128 to the ASCII value in order to turn the added bit to 1.
If the value is even, the new bit must be 0. Therefore, check, as above, if the new value, once bitshifted, is larger than 127. If this is the case, subtract 128. Else, do nothing. This will make sure the added bit is 0.
PRACTICE :
Code:void bse() // BitShift Encrypt { int b = (int)a; // a is char a; the character being encrypted. if(b > 127) { a = (a << 1); a = (a | 1); } else if(b < 128) { a = (a << 1); if(a % 2 == 1) a = a - 1; } } void bsd() // BitShift Decrypt { int b = (int)a; if((b % 2) == 1) { a = (a >> 1); int c = (int)a; if(c < 127) a = a + 128; } else if((b % 2) == 0) { a = (a >> 1); int c = (int)a; if(c > 127) a = a - 128; } }
For some reason that escapes me, this code only works for ASCII values larger than 127, and I cannot see the problem...
Korhedron