Do I understand this correctly? You have a character set and you want to shift (like, encrypt) the characters of that file? You have 0-255 possible values, so you should shift them by an integer between 0-255, because if you add 256 to a character code, you get the same code, so it has no point. If so, then it should look something like this:
Here you have a problem though. If you use different KEY's for different files, then you have no way knowing what KEY you used for a particular file.
#define KEY 60 //anywhere from 0 to 255 - the number to add to each character code
int main(int argc,char *argv)
if (*(argv+1)) //assume the 1st argument is the filename
if (infile = fopen(argv+1,"rb") //open the file in binary mode
outfile = fopen("encrypted.txt","wb"); //create or rewrite the new, encrypted file
while (c = fgetc(infile))
fputc(c + KEY,outfile);
So to retrieve the message back, you should either use the SAME key everywhere, or just write the key into the encrypted file as the first byte. For example, say your text file contains this: "secret".
That's 6 bytes. Now, when you write the encrypted file, you first write the KEY, as the first bit. If your key is 60, you'll write 60 as the first byte, which is '<' in a symbol notation. And, when shifting all of your file's characters forward by 60, you'll get the following file:
in decimal notation:
So, when later reading the file, you first read the key:
and then you'll read the file character by characer:
fp = fopen("encrypted.txt","rb");
key = fgetc(fp); //the first byte in the file
Or something similar.. You get the idea.
contents[i] = fgetc(fp) - key; // fgetc(fp) - key gives the original character back
EDITED TO ADD:
What you can't do, is use the left shift operator (the << operator) for this encryption. Why? Consider this:
Assume you have a character in the file: 'a'
in bit representation it's:
Now say you shift these bits to the left by four, eg you do:
What you actually do is this:
a <<= 4; // or, a = a << 4;
01100001 << 4 = 00010000
meaning, by shifting the bits left by 4, you fill the lower 4 bits with zeros and the higher 4 bits will become, what were the lower 4 bits, previously. But the previous higher 4 bits - '0110' will dissapear. Now you encrypted "01100001" into "00010000". But when later decrypting it, if you shift the bits back to left: 00010000 >> 4 = 00000001, because shifting bits right will simply bring zeros in from the right. You can and never will have any knowledge, of what the encrypted character used to be, since you can't know, what the previously left shifted 4 bits were.
So the only way you can do this "shifting"-encryption, is by adding or subtracting a certain integer value of 0-255 from each character in the file and remembering that value, which is the KEY for later decrypting the data as well.