When doing character arithmetic is it a rule that you perform the calculations in base 10 or base 8? My book says 'A' = 101 in base 8 or 65 base 10 but when I insert the character values in base 8 into an example my book gives about illustrating this point i get some funny results. The code below is an example in my book for a Ceaser Cipher that tries to find the new character. If I try to convert 'Y' and shift 8 spots to find a new character and if ch = 'Y' and n = 8 I'm expecting to get character 'G'.
ch = (char)('A' + (Character.toUpperCase(ch) - 'A' + n) % 26);
the math works out to
65 + (89 - 65 + 8) % 26 = 71 (base 10)
101 + (131 - 101 + 8) % 26 = 113 (base 8)
If i convert the 71 (base 10) back into base 8, I'll get 107 which is character 'G' which is the correct character. My question is why I can't perform character arithmetic in base 8? 113 is character 'K' which is the wrong character. Is the rule when doing character arithmetic to convert all the values into base 10 and then convert them back into base 8?
Computers store values in memory. Everything else is a convenience for our dumb human brains (and eyes). By default, in Java any textual output of those values is going to be in base10 (decimal).
Ais 65 in base10, and 101 in base8 (provided we're talking about a character set that preserves US-ASCII values).When talking about literals in Java, by default they are interpreted as base10. To use an octal literal, you need to precede it by a
0:The above will output
true.If you want to in your example, you can set
nvia an octal literal or parse an octalStringto an int, you get the result you expect:outputs:
You could also parse an octal
Stringforn:The issue you're really facing here is trying to do base8 math, but performing base10 arithmetic (and you left
nas decimal8):Java interprets those literals as base10 representations, and that most certainly will result in:
On the other hand, were you to use octal literals and do the same...
Outputs: