2

So I'm I just started pest 2 and it was pretty smooth until I found a horrible bug in my code. Essentially the code works fine when the entire plain text string is in upper case, but it gives me a strange question mark symbol in lower case. I attempted to debug using GDB and I noticed that everything works fine, but when it gets to the line where the key number is added to the actual character, the Ascii value goes from positive to negative, which completely blew my mind, I've tried casting and using the absolute value of the addition and nothing seems to work : | Any suggestions?

    // if lowercase
        plaintext[i] = (plaintext[i] + key); //  ascii went negative

1 Answer 1

5

By defaults, chars are signed values in the range -128 to 127. If, say, your plaintext[i] is 'x' (ie, 120) and you add a key of 10, you don't get 130. Instead, you get -126.

Signed integers (chars) count like this, adding 1.

120
121
122
123
124
125
126
127
-128
-127
-126

One way around this is to cast your char to an unsigned char when you do your "if it's >122" check; that way, the comparison will be done against 130 rather than -126.

if ((unsigned char) plaintext[i] > 122)  etc.

This caught me out as well.

Brenda.

4
  • Thanks a lot!!! That solved it. I don't think I would have figured that out myself lol
    – vanugrah
    Jun 23, 2014 at 22:46
  • You're welcome. -Brenda.
    – curiouskiwi
    Jun 23, 2014 at 22:50
  • Where in the world would I have come across this numbering for ASCII chars? I have watched and re-watched all walkthrus and shorts. I printed an ASCII chart after a generic Google search that does not include negative numbering. I made the change to my program and now it works but I feel like I didn't solve the problem. It feels like I used your thinking and it's no longer my solution. My week2 notes run to 32 pages including annotated screenshots. Nowhere can I find reference to unsigned chars. Sep 12, 2014 at 18:01
  • Ah! I had the same problem... was able to figure out what the bug was by checking out the 'man ascii' (Joseph, that's how I found this)... but hadn't figured out how to fix it until now-- thank you curiouskiwi. Another question though-- it seems to me like pretty much _every_body would have this issue, no? And it doesn't seem all that common, which makes me wonder-- is there a better or more direct way to do this that doesn't lead to the same problem? Do we ever get to see the 'most elegant' solutions to these problems? Nov 24, 2014 at 11:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .