ROT13 one ASCII character

0

This kind of question has been asked before, but I wanted to make it more specific. The linked question asks to read from stdin and rot13 the input. I don't want the disadvantage of I/O code that differs a lot for each language in length.

The challenge:

Write a function that will ROT13 (wiki link) one char (as defined by the ASCII table).
No built-in ROT13 functionality allowed.

Shortest code wins.


You can use this kind of C-family loop to test your function:

for (int i = '!'; i <= '~'; ++i)
{
    char c = (char) i;
    System.out.println(c + "   ->   " + f(c));
}

Martijn Courteaux

Posted 2014-01-02T17:45:51.070

Reputation: 759

Question was closed 2014-01-02T18:11:35.120

@Howard: I linked that question myself. But that is different. Here the task is to rotate only one char. – Martijn Courteaux – 2014-01-02T17:49:23.803

The difference is minor only - almost all answers from the other question can be user with litte modifications. – Howard – 2014-01-02T17:50:00.097

@Howard: The most important difference is that I don't want the I/O code here. Just the plain algorithm. – Martijn Courteaux – 2014-01-02T17:52:06.067

2In my opinion changing I/O doesn't justify a new question in this case. – Howard – 2014-01-02T17:55:56.947

Answers

3

C (77 64 chars)

char f(char c){return(c>64&&c<91)?65+(c-52)%26:(c>96&&c<123)?97+(c-84)%26:c;}

char f(char c){return(isalpha(c))?65+(c&32)+(c-52-(c&32))%26:c;}

mcleod_ideafix

Posted 2014-01-02T17:45:51.070

Reputation: 901

1

I came up with this in Java (81 chars):

char f(char c){return Character.isLetter(c)?(char)((((c&95)-52)%26+65)|c&32):c;}

Demo here: http://ideone.com/ItT7IM

Martijn Courteaux

Posted 2014-01-02T17:45:51.070

Reputation: 759