Question

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?

Was it helpful?

Solution

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).

A is 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:

int a1 = 65;   // literals are by default base10
int a2 = 0101; // an octal literal in Java is preceded by a 0
int a3 = 'A';
System.out.println(a1 == a2 && a2 == a3); 

The above will output true.

If you want to in your example, you can set n via an octal literal or parse an octal String to an int, you get the result you expect:

int n = 010; // octal literal equal to decimal 8
int a = 'A' + ('Y' - 'A' + n) % 26;
System.out.println(a);
System.out.println(Integer.toOctalString(a));

outputs:

71
107

You could also parse an octal String for n:

int n = Integer.valueOf("010", 8);

The issue you're really facing here is trying to do base8 math, but performing base10 arithmetic (and you left n as decimal 8):

int o = 101 + (131 - 101 + 8) % 26;
System.out.println(o);
System.out.println(Integer.toOctalString(o));

Java interprets those literals as base10 representations, and that most certainly will result in:

113
161

On the other hand, were you to use octal literals and do the same...

int o = 0101 + (0131 - 0101 + 010) % 26;
System.out.println(o);
System.out.println(Integer.toOctalString(o));

Outputs:

71
107

OTHER TIPS

I think your problem is that the modulo function cannot use "26" in both cases -- 26(base 8) is 22 decimal; there are 32(base 8) characters in the English alphabet. Try your base 8 calculations with

... % 32(base 8)

instead of with 26(base 8).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top