-
May 15th, 2011, 01:32 AM
#1
ROT13 ******* addition turns value negative :s
So I'm writing a program to process simple ROT13 encryption (where you read in a string and move each letter 13 places across in the alphabet to hide it, then if you do it again, it reverts back to it's original text). eg. 'HELLO' would encrypt to 'URYYB'
My code works for all values, uppercase and lowercase, except for lowercase 's' through to 'z' (ascii values 115 to 122)
I ran it through a debugger and saw that when the line (i commented at the line im talking about) in the code which should only +13 to its value, turns 115 into -128, instead of 128. This gives me a weird value and i can't figure out why.
Code:
void encrypt(char *input, int upperindex, int lowerindex)
{
int i;
for(i = 0; i < SIZE; i++)
{
/** THIS IS FOR LOWERCASE CHARACTERS**/
if((input[i]<123) &&(input[i]>96))
{
input[i] = input[i] + 13; /** THIS IS THE LINE THAT GOES WRONG**/
if(input [i] > 122)
{
input[i] = lowerindex + ( (input[i]) % 122 );
}
}
/** THIS IS FOR UPPERCASE CHARACTERS**/
if((input[i]<91)&&(input[i]>64))
{
input[i] = input[i] + 13;
if(input[i] > 90)
{
input[i] = upperindex + ( (input[i]) % 90);
}
}
}
}
can someone help me out as to what could be making this code go wrong for only select values?
-
May 15th, 2011, 01:41 AM
#2
Re: ROT13 ******* addition turns value negative :s
char is signed value, with range from -128 to 127. If you need 0-255 range, use unsigned char.
-
May 15th, 2011, 01:50 AM
#3
Re: ROT13 ******* addition turns value negative :s
Thankyou,
Out of curiosity/understanding, what advantage is there of having a signed char limited to -128 to 127?
-
May 15th, 2011, 02:04 AM
#4
Re: ROT13 ******* addition turns value negative :s
Originally Posted by BJ2
Thankyou,
Out of curiosity/understanding, what advantage is there of having a signed char limited to -128 to 127?
chars are 1 byte, so the largest and smallest number possible is -128 and 127, respectively, if the char is signed.
Regards,
Paul McKenzie
-
May 16th, 2011, 07:09 AM
#5
Re: ROT13 ******* addition turns value negative :s
Originally Posted by BJ2
Thankyou,
Out of curiosity/understanding, what advantage is there of having a signed char limited to -128 to 127?
Negative values.
-
May 16th, 2011, 08:19 PM
#6
Re: ROT13 ******* addition turns value negative :s
Originally Posted by BJ2
Thankyou,
Out of curiosity/understanding, what advantage is there of having a signed char limited to -128 to 127?
To expand on what Paul & GCDEF said, a char is 1 byte - it can have 256 possible values.
If it is unsigned, those values are in the range 0 - 255
If it is signed, those values are in the range -128 - +127.
If you want to understand further... http://en.wikipedia.org/wiki/Two's_complement
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|