I have a binary file that will be read in as characters. Each character was bit shifted to the left unknown number of times (assuming with wrap) by someone else. I want to be able to read in each character and then wrap shift to the right (the number of times to shift I guess will have to be figured out manually, because I haven't figured out another way).
So, my current idea is that I read in a character, create a copy with temp and then use XOR:
char letter; //will hold the read in letter
char temp; //will hold a copy of the letter
while(file.read(&letter, sizeof(letter)) //letter now holds 00001101
{
temp = letter; //temp now holds 00001101
letter >>= 1; //shift 1 position to the right, letter now holds 00000110
temp <<= 7; //shift to the left by (8-1), which is 7, temp now holds 10000000
letter ^= temp; //use XOR to get the wrap, letter now holds 10000110
cout << letter;
}
That makes sense in my exhausted head, but it doesn't work... and I can't figure out why. Size of char is 1 byte, so I figured I only have to mess around with 8 bits.
Any help would be appreciated.
EDIT: Solved. Thanks so much to everyone. Love this community to death, you guys are awesome!
What are bit shifting operators available in C ? Give examples. Bitshift operators are used to move the bits of a variable in a perticular direction. The right shift operator (>>) shifts each bit inside a variable a certain number of places to the right.
According to the program’s requirements, a bitwise shift operator shifts the binary bits left or right. Integer values are applied to these operators (int, long, possibly short, and byte or char). In some languages, using the shift operators on any data type smaller than int automatically resizes the operand to be an int.
The program should output the characters in their bit format before and after they are packed into the unsigned integer to prove that they are in fact packed correctly in the unsigned variable.
To unpack two characters from an unsigned two-byte integer, combine the unsigned integer with the mask 65280 ( 11111111 00000000) and right-shift the result 8 bits. Assign the resulting value to a char variable.
Pay attention to the signess of a char. On many systems it is signed. So your letter >>= 1
is sign filling the shift.
Rotating integers is usually done as follows
letter = ((unsigned char)letter >> 1) | (letter << 7);
As Mark points out in the comments, you can use either OR |
or XOR ^
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With