Caesar cipher: Difference between revisions
m
syntax highlighting fixup automation
Cyril Nocton (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 25:
=={{header|11l}}==
<
I decode
key = 26 - key
Line 44:
V enc = caesar(msg, 11)
print(enc)
print(caesar(enc, 11, decode' 1B))</
{{out}}
<pre>
Line 54:
=={{header|360 Assembly}}==
A good example of the use of TR instruction to translate a character.
<
CAESARO PROLOG
XPRNT PHRASE,L'PHRASE print phrase
Line 83:
ORG
YREGS
END CAESARO</
{{out}}
<pre>
Line 92:
=={{header|8th}}==
<
: modulate \ char base -- char
tuck n:- 26 n:+ 26 n:mod n:+ ;
Line 114:
1 caesar dup . cr
-1 caesar . cr
bye</
{{out}}
<pre>
Line 123:
=={{header|Action!}}==
<
CHAR base
Line 165:
Test("The quick brown fox jumps over the lazy dog.",23)
Test("The quick brown fox jumps over the lazy dog.",5)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Caesar_cipher.png Screenshot from Atari 8-bit computer]
Line 185:
=={{header|Ada}}==
<
procedure Caesar is
Line 229:
Ada.Text_IO.Put_Line("Decrypted Ciphertext ->" & crypt(Text, -Key));
end Caesar;</
{{out}}
<pre>> ./caesar
Line 242:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<
program caesar: BEGIN
Line 284:
printf(($gl$, "Decrypted Ciphertext ->" + encrypt(text, -key)))
END #caesar#</
{{out}}
<pre>
Line 293:
=={{header|APL}}==
<
∇CAESAR[⎕]∇
∇
Line 301:
[3] A←V
∇
</syntaxhighlight>
{{out}}
<pre>
Line 325:
=={{header|AppleScript}}==
<
on caesarDecipher(txt, |key|)
Line 351:
set enciphered to caesarEncipher(txt, |key|)
set deciphered to caesarDecipher(enciphered, |key|)
return "Text: '" & txt & ("'" & linefeed & "Key: " & |key| & linefeed & linefeed) & (enciphered & linefeed & deciphered)</
{{output}}
<
The quick brown fox jumps over the lazy dog.'
Key: 9
Line 362:
Cqn zdrlt kaxfw oxg sdvyb xena cqn ujih mxp.
ROMANES EUNT DOMUS!
The quick brown fox jumps over the lazy dog."</
=={{header|Applesoft BASIC}}==
<
110 LET K% = RND(1) * 25 + 1
Line 406:
460 IF C > 90 THEN C = C - 26
470 LET C$ = CHR$(C + L)
480 RETURN</
{{out}}
<pre>]RUN
Line 430:
=={{header|Arc}}==
<
(= rot (fn (L N)
(if
Line 451:
(string output)
))
</syntaxhighlight>
{{Out}}
<
(caesar "The quick brown fox jumps over the lazy dog.")
"Gur dhvpx oebja sbk whzcf bire gur ynml qbt."
</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<
/* ARM assembly Raspberry PI */
/* program caresarcode.s */
Line 635:
bx lr @ return
</syntaxhighlight>
=={{header|Arturo}}==
{{trans|11l}}
<
iA: to :integer `A`
lowAZ: `a`..`z`
Line 661:
enc: caesar msg 11
print [" Encoded :" enc]
print [" Decoded :" caesar.decode enc 11]</
{{out}}
Line 670:
=={{header|Astro}}==
<
if decode:
k = 26 - k
Line 682:
let decrypted = caesar(enc, 11, decode: true)
print(message, encrypted, decrypted, sep: '\n')</
=={{header|AutoHotkey}}==
This ungodly solution is an attempt at code-golf. It requires input to be all-caps alphabetic, only works on AutoHotkey_L Unicode, and might not run on x64
<
s=HI
t:=&s
While *t
o.=Chr(Mod(*t-65+n,26)+65),t+=2
MsgBox % o</
This next one is much more sane and handles input very well, including case.
<
Loop Parse, string
{
Line 705:
}
MsgBox % Caesar("h i", 2) "`n" Caesar("Hi", 20)</
{{out}}<pre>j k
Bc</pre>
Line 712:
The Ceasar Funktion can enrcypt and decrypt, standart is Encryption, to Decrypt set third parameter to False
<
$Caesar = Caesar("Hi", 2, True)
MsgBox(0, "Caesar", $Caesar)
Line 745:
Return $sLetters
EndFunc ;==>Caesar
</syntaxhighlight>
=={{header|AWK}}==
<
#!/usr/bin/awk -f
Line 791:
return s
}
</syntaxhighlight>
{{out}}
Line 802:
=={{header|Babel}}==
<
{"The quick brown fox jumps over the lazy dog.\n"
dup <<
Line 853:
<- 0x60 cugt ->
0x7b cult
cand }))</
{{out}}
Line 861:
=={{header|BaCon}}==
<
CONST uc$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Line 881:
PRINT "Encrypted: ", en$
PRINT "Decrypted: ", Ceasar$(en$, 26-tokey)</
{{out}}
<pre>
Line 899:
{{works with|GNU bash, version 4}}
<
caesar_cipher() {
Line 941:
}
</syntaxhighlight>
{{out}} (input: caesar_cipher -e 13 "Hello World!"):
Line 954:
=={{header|BASIC256}}==
<syntaxhighlight lang=text>
# Caeser Cipher
# basic256 1.1.4.0
Line 985:
next i
</syntaxhighlight>
{{out}}
<pre>
Line 998:
=={{header|BBC BASIC}}==
<
PRINT plaintext$
Line 1,020:
NEXT
= text$
</syntaxhighlight>
{{out}}
<pre>Pack my box with five dozen liquor jugs
Line 1,027:
=={{header|Beads}}==
<
calc main_init
var str = "The five boxing wizards (🤖) jump quickly."
Line 1,059:
) : str
// we could also just shift by 26-nshift, same as going in reverse
return Encrypt(input, -nshift)</
{{out}}
<pre>Plain: The five boxing wizards (🤖) jump quickly.
Line 1,071:
The text to encrypt is read from stdin, and the key is the first integer on the stack - 11 (<tt>65+</tt>) in the example below.
<
"`"::_@#!`\*84:<~<$<^+"A"%*2+9<v"{"\`
**-"A"-::0\`\55*`+#^_\0g+"4"+4^>\`*48</
{{out}}
Line 1,081:
The decrypter is essentially identical, except for a change of sign on the last line.
<
"`"::_@#!`\*84:<~<$<^+"A"%*2+9<v"{"\`
**-"A"-::0\`\55*`+#^_\0g-"4"+4^>\`*48</
{{out}}
Line 1,090:
=={{header|BQN}}==
<
Rot ← {i←⊑"A[a{"⍋𝕩 ⋄ i⊑o+p|(𝕨×m)+𝕩-o}⎉0</
Example:
<
<pre>"Zh'uh qr vwudqjhuv wr oryh // Brx nqrz wkh uxohv dqg vr gr L"</pre>
Line 1,101:
=={{header|Brainf***}}==
<
+ start the key input loop
Line 1,317:
^
<< :c ^
]</
Usage:
Give to the program the key and the word to encrypt, each followed by a space.<br>
Input:
<!-- Using whitespace syntax highlighting to show the spaces, used by the program to separate arguments -->
<syntaxhighlight lang
Output:
<pre>klm</pre>
Input:
<syntaxhighlight lang
Output:
<pre>abc</pre>
=={{header|C}}==
<
#include <stdlib.h>
#include <string.h>
Line 1,382:
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Linq;
Line 1,424:
}
}
}</
{{out}}
<pre>Pack my box with five dozen liquor jugs.
Line 1,431:
=={{header|C++}}==
<
#include <iostream>
#include <algorithm>
Line 1,475:
std::cout << input << std::endl ;
return 0 ;
}</
{{out}}
<pre>Which text is to be encrypted ?
Line 1,494:
===={{works with|C++-11}}====
<
#include <string>
Line 1,548:
return 0 ;
}
</syntaxhighlight>
{{out}}
Line 1,563:
=={{header|Clojure}}==
Readable version:
<
(if (Character/isLetter c)
(let [v (int c)
Line 1,585:
(print "Original text:" text "\n")
(print "Encryption:" enc "\n")
(print "Decryption:" (decrypt -1 enc) "\n"))</
output:
Line 1,594:
Terser version using replace:
<
(let [f #(take 26 (drop %3 (cycle (range (int %1) (inc (int %2))))))
a #(map char (concat (f \a \z %) (f \A \Z %)))]
Line 1,600:
(defn decode [k s]
(encode (- 26 k) s))</
output:<pre>
Line 1,611:
=={{header|COBOL}}==
COBOL-85 ASCII or EBCIDIC
<
identification division.
program-id. caesar.
Line 1,649:
.
end program caesar.
</syntaxhighlight>
{{out}}
<pre>
Line 1,658:
{{works with|OpenCOBOL|2.0}}
<
PROGRAM-ID. caesar-cipher.
Line 1,743:
MOVE FUNCTION encrypt(decrypt-offset, str) TO decrypted-str
.
END FUNCTION decrypt.</
{{out}}
Line 1,754:
=={{header|CoffeeScript}}==
<
msg.replace /([a-z|A-Z])/g, ($1) ->
c = $1.charCodeAt(0)
Line 1,763:
console.log cipher "Hello World", 2
console.log cipher "azAz %^&*()", 3</
{{out}}
<pre>
Line 1,775:
Very generic implementation. Please note that in Commodore BASIC, SHIFT-typed letters (to generate either graphic symbols in upper-case mode, or capital letters in lower-case mode) do '''not''' translate to PETSCII characters 97 through 122, but instead to characters 193 through 218.
<
2 rem rosetta code
10 print chr$(147);chr$(14);
Line 1,821:
3035 cm$=cm$+mid$(ec$,c,1)
3040 next i
3050 return</
{{Output}}
Line 1,850:
=={{header|Common Lisp}}==
====Main version====
<
(let* ((c (char-code ch)) (la (char-code #\a)) (ua (char-code #\A))
(base (cond ((<= la c (char-code #\z)) la)
Line 1,868:
(format t " Original: ~a ~%" original-text)
(format t "Encrypted: ~a ~%" cipher-text)
(format t "Decrypted: ~a ~%" recovered-text))</
{{out}}
<pre> Original: The five boxing wizards jump quickly
Encrypted: Wkh ilyh eralqj zlcdugv mxps txlfnob
Decrypted: The five boxing wizards jump quickly</pre>
<
(defun caesar-encipher (s k)
(map 'string #'(lambda (c) (z c k)) s))
Line 1,883:
(when (<= 65 c 90) 65))))
(if b (code-char (+ (mod (+ (- c b) k) 26) b)) h))
</syntaxhighlight>
{{out}}
<pre>
Line 1,894:
1. Program
<
(defun caesar (txt offset)
Line 1,902:
(char +a+ (mod (+ (position c +a+) (* 2 offset)) 52))
c))
txt))</
2. Execution
Line 1,913:
=={{header|Crystal}}==
<
ALPHABET = ("A".."Z").to_a
Line 1,924:
encrypted = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG".caesar_cipher(5)
decrypted = encrypted.caesar_cipher(-5)
</syntaxhighlight>
=={{header|Cubescript}}==
<
//Cubescript's built-in mod will fail on negative numbers
Line 1,984:
] ]
result $arg1
]</
Usage:
<syntaxhighlight lang=text>>>> cipher "The Quick Brown Fox Jumps Over The Lazy Dog." 5
> Ymj Vznhp Gwtbs Ktc Ozrux Tajw Ymj Qfed Itl.
>>> decipher "Ymj Vznhp Gwtbs Ktc Ozrux Tajw Ymj Qfed Itl." 5
> The Quick Brown Fox Jumps Over The Lazy Dog.</
=={{header|D}}==
<
S rot(S)(in S s, in int key) pure nothrow @safe
Line 2,014:
writeln("Encrypted: ", txt.rot(key));
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
}</
{{out}}
<pre>Original: The five boxing wizards jump quickly
Line 2,020:
Decrypted: The five boxing wizards jump quickly</pre>
Simpler in-place version (same output):
<
void inplaceRot(char[] txt, in int key) pure nothrow {
Line 2,039:
txt.inplaceRot(26 - key);
writeln("Decrypted: ", txt);
}</
A version that uses the standard library (same output):
<
string rot(in string s, in int key) pure nothrow @safe {
Line 2,058:
writeln("Encrypted: ", txt.rot(key));
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
}</
=={{header|Dart}}==
<
int _key;
Line 2,124:
trip(".-:/\"\\!");
trip("The Quick Brown Fox Jumps Over The Lazy Dog.");
}</
{{out}}
<pre>JK
Line 2,154:
{{trans|C#}}
<
if !this.IsLetter() {
return this
Line 2,179:
print("Encrypted: \(str)")
str = str.Decrypt(5)
print("Decrypted: \(str)")</
{{out}}
Line 2,200:
If the program is running in the EdsacPC simulator, the user can enter a message by storing it in a text file, making that file the active file, and clicking Reset.
The message must be terminated by a blank row of tape (represented by '.' in EdsacPC).
<
[Caesar cipher for Rosetta Code.
EDSAC program, Initial Orders 2.]
Line 2,416:
P F [acc = 0 on entry]
DGAZA!FREQUENS!LIBYCUM!DUXIT!KARTHAGO!TRIUMPHUM.
</syntaxhighlight>
{{out}}
<pre>
Line 2,431:
=={{header|Eiffel}}==
<
class
APPLICATION
Line 2,485:
end
end
</syntaxhighlight>
{{out}}
<pre>
Line 2,495:
=={{header|Ela}}==
<
chars = "ABCDEFGHIJKLMOPQRSTUVWXYZ"
Line 2,522:
putStrLn ""
putStr "Decoded string: "
put $ decypher key cstr</
{{out}}
Line 2,533:
=={{header|Elena}}==
ELENA 4.x :
<
import system'math;
import extensions;
Line 2,607:
console.readChar()
}</
{{out}}
<pre>
Line 2,616:
=={{header|Elixir}}==
<
defp set_map(map, range, key) do
org = Enum.map(range, &List.to_string [&1])
Line 2,633:
IO.puts "Original: #{text}"
IO.puts "Encrypted: #{enc = Caesar_cipher.encode(text, key)}"
IO.puts "Decrypted: #{Caesar_cipher.encode(enc, -key)}"</
{{out}}
Line 2,643:
=={{header|Erlang}}==
<
%% Ceasar cypher in Erlang for the rosetta code wiki.
%% Implemented by J.W. Luiten
Line 2,678:
PlainText = lists:map(fun(Char) -> rot(Char, Decode) end, CypherText).
</syntaxhighlight>
Command: <
{{out}}
<pre>
Line 2,688:
=={{header|ERRE}}==
<
PROGRAM CAESAR
Line 2,718:
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 2,728:
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.0}}
<
--caesar cipher for Rosetta Code wiki
--User:Lnettnay
Line 2,784:
printf(1,"%s\n",{text})
</syntaxhighlight>
{{out}}
<pre>
Line 2,793:
=={{header|F_Sharp|F#}}==
<
open System
Line 2,805:
let encrypt n = cipher n
let decrypt n = cipher (26 - n)</
<pre>> caesar.encrypt 2 "HI";;
val it : string = "JK"
Line 2,819:
{{works with|Factor|0.97}}
{{trans|F#}}
<
IN: rosetta-code.caesar-cipher
Line 2,836:
11 "Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr." decrypt print
11 "The quick brown fox jumped over the lazy dog." encrypt print</
{{out}}
<pre>
Line 2,847:
Shifts upper/lower case letters, leaves other characters as they are.
<
class Main
{
Line 2,900:
}
}
</syntaxhighlight>
Example:
Line 2,922:
=={{header|Fhidwfe}}==
only encodes letters
<
lowers = ['a','z']
uppers = ['A','Z']
Line 2,965:
//this compiles with only 6 warnings!
</syntaxhighlight>
=={{header|Forth}}==
<
over 32 or [char] a -
dup 0 26 within if
Line 2,986:
3 ceasar-inverse test 2@ ceasar-string
test 2@ cr type</
=={{header|Fortran}}==
{{works with|Fortan 90 and later}}
<
implicit none
Line 3,032:
end subroutine
end program Caesar_Cipher</
{{out}}
<pre>Original message = The five boxing wizards jump quickly
Line 3,039:
=={{header|FreeBASIC}}==
<
Sub Encrypt(s As String, key As Integer)
Line 3,079:
Decrypt s, 8
Print "Decrypted : "; s
Sleep</
{{out}}
Line 3,090:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=cb96008082bc0d8278224cd2a5ec74d3 Click this link to run this code]'''
<
Dim byKey As Byte = 3 'The key (Enter 26 to get the same output as input)
Dim byCount As Byte 'Counter
Line 3,109:
Print sString & gb.NewLine & sCoded 'Print the result
End</
Output:
<pre>
Line 3,117:
=={{header|GAP}}==
<
local r, c, i, lower, upper;
lower := "abcdefghijklmnopqrstuvwxyz";
Line 3,142:
CaesarCipher("Vgg cphvi wzdibn vmz wjmi amzz viy zlpvg di ydbidot viy mdbcon.", 5);
# "All human beings are born free and equal in dignity and rights."</
=={{header|GFA Basic}}==
<
'
' Caesar cypher
Line 3,182:
RETURN @encrypt$(text$,26-key%)
ENDFUNC
</syntaxhighlight>
=={{header|Go}}==
Obvious solution with explicit testing for character ranges:
<
import (
Line 3,244:
fmt.Println(" Deciphered:", ck.decipher(ct))
}
}</
Data driven version using functions designed for case conversion. (And for method using % operator, see [[Vigen%C3%A8re_cipher#Go]].)
<
import (
Line 3,302:
fmt.Println(" Deciphered:", ck.decipher(ct))
}
}</
{{out}} (either version)
<pre>
Line 3,321:
=={{header|Groovy}}==
Java style:
<
def builder = new StringBuilder()
text.each { character ->
Line 3,333:
builder as String
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</
Functional style:
<
text.chars.collect { c ->
int off = c.isUpperCase() ? 'A' : 'a'
Line 3,342:
}.join()
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</
Ninja style:
<
(text as int[]).collect { it==' ' ? ' ' : (((it & 0x1f) + k - 1) % 26 + 1 | it & 0xe0) as char }.join()
}
def caesarDecode(k, text) { caesarEncode(26 - k, text) }</
Using built in 'tr' function and a replacement alphabet:
<
text.tr('a-zA-Z', ((('a'..'z')*2)[k..(k+25)] + (('A'..'Z')*2)[k..(k+25)]).join())
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</
and the same with closures for somewhat better readability:
<
def c = { (it*2)[k..(k+25)].join() }
text.tr('a-zA-Z', c('a'..'z') + c('A'..'Z'))
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</
Test code:
<
def plainText = "The Quick Brown Fox jumped over the lazy dog"
def cipherKey = 12
Line 3,373:
assert plainText == decodedText
</syntaxhighlight>
{{out}}
Line 3,381:
=={{header|Haskell}}==
<
import Data.Char
Line 3,397:
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c
</syntaxhighlight>
And trying it out in GHCi:
Line 3,409:
Similarly, but allowing for negative cipher keys, and using isAlpha, isUpper, negate:
<
import Data.Char (chr, isAlpha, isUpper, ord)
Line 3,432:
cipher = caesar k
plain = "Curio, Cesare venne, e vide e vinse ? "
mapM_ putStrLn $ [cipher, uncaesar k . cipher] <*> [plain]</
{{Out}}
<pre>Skhye, Suiqhu luddu, u lytu u lydiu ?
Line 3,438:
Or with proper error handling:
<
module Main where
Line 3,469:
addChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26)
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c</
=={{header|Hoon}}==
<
++ enc
|= [msg=tape key=@ud]
Line 3,480:
|= [msg=tape key=@ud]
(enc msg (sub 26 key))
--</
=={{header|Icon}} and {{header|Unicon}}==
Strictly speaking a Ceasar Cipher is a shift of 3 (the default in this case).
<
ctext := caesar(ptext := map("The quick brown fox jumped over the lazy dog"))
dtext := caesar(ctext,,"decrypt")
Line 3,499:
"d"|"decrypt" : return map(text,(&lcase||&lcase)[k+:*&lcase],&lcase)
}
end</
{{out}}
Line 3,507:
=={{header|IS-BASIC}}==
<
110 STRING M$*254
120 INPUT PROMPT "String: ":M$
Line 3,547:
480 NEXT
490 LET M$=T$
500 END DEF</
=={{header|J}}==
If we assume that the task also requires us to leave non-alphabetic characters alone:
<
caesar=: (cndx 0)}&a.@u:@cndx@[ {~ a.i.]</
Example use:<
Vjku ukorng "oqpqcnrjcdgvke uwduvkvwvkqp ekrjgt" rtqxkfgu cnoquv pq ugewtkva, ...</
If we instead assume the task only requires we treat upper case characters:
<
Example use:<
BC</
=={{header|Janet}}==
<
(def alphabet "abcdefghijklmnopqrstuvwxyz")
Line 3,590:
(print cipher)
(print str)))
</syntaxhighlight>
{{out}}
Line 3,602:
=={{header|Java}}==
{{works with|Java|1.5+}}
<
public static void main(String[] args) {
Line 3,631:
return encoded.toString();
}
}</
{{out}}
<pre>
Line 3,642:
===ES5===
<
return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/./g, function(a) {
return String.fromCharCode(65+(a.charCodeAt(0)-65+shift)%26);
Line 3,652:
for (var i = 0; i<26; i++) {
console.log(i+': '+caesar(text,i));
}</
{{output}}
Line 3,665:
===ES6===
<
.toUpperCase()
.replace(/[^A-Z]/g, '')
.replace(/./g, a =>
String.fromCharCode(65 + (a.charCodeAt(0) - 65 + shift) % 26));</
Or, allowing encoding and decoding of both lower and upper case:
<
// Int -> String -> String
Line 3,716:
return [strCipher, ' -> ', strDecode];
})(114, 'Curio, Cesare venne, e vide e vinse ? ');</
{{Out}}
Line 3,725:
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<
. as $s
| explode as $xs
Line 3,755:
(encrypt(8)
| ., decrypt(8) )
</syntaxhighlight>
{{out}}
<pre>
Line 3,766:
=={{header|Jsish}}==
From Typescript entry.
<
"use strict";
Line 3,798:
caesarCipher(caesarCipher(str, 3), -3) ==> The five boxing wizards jump quickly
=!EXPECTEND!=
*/</
{{out}}
Line 3,807:
===updated version for Julia 1.x | Rename isalpha to isletter #27077 | https://github.com/JuliaLang/julia/pull/27077===
<
# Caeser cipher
# Julia 1.5.4
Line 3,840:
text = "Magic Encryption"; key = 13
csrcipher(text, key)
</syntaxhighlight>
{{out}}
<pre>
Line 3,850:
Assumes lowercase letters, and no punctuation.
<syntaxhighlight lang=k>
s:"there is a tide in the affairs of men"
caesar:{ :[" "=x; x; {x!_ci 97+!26}[y]@_ic[x]-97]}'
caesar[s;1]
"uifsf jt b ujef jo uif bggbjst pg nfo"
</syntaxhighlight>
=={{header|Kotlin}}==
<
object Caesar {
Line 3,892:
val decoded = Caesar.decrypt(encoded, 8)
println(decoded)
}</
{{out}}
Line 3,905:
=={{header|Lambdatalk}}==
The caesar function encodes and decodes texts containing exclusively the set [ABCDEFGHIJKLMNOPQRSTUVWXZ].
<
{def caesar
Line 3,975:
-> VENIVIDIVICI
</syntaxhighlight>
=={{header|langur}}==
Using the built-in rotate() function on a number over a range, a number outside of the range will pass through unaltered.
<
cp2s map(f(.c) rotate(rotate(.c, .key, 'a'..'z'), .key, 'A'..'Z'), s2cp .s)
}
Line 3,989:
writeln " original: ", .s
writeln "encrypted: ", .rot(.s, .key)
writeln "decrypted: ", .rot(.rot(.s, .key), -.key)</
{{out}}
Line 3,997:
=={{header|Liberty BASIC}}==
<
Print "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 4,020:
CaesarCypher$ = (CaesarCypher$ + Chr$(rotate))
Next i
End Function</
=={{header|LiveCode}}==
<
local rotPhrase, lowerLetters, upperLetters
put "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" into lowerLetters
Line 4,038:
end repeat
return rotPhrase
end caesarCipher</
=={{header|Logo}}==
{{trans|Common Lisp}}
{{works with|UCB Logo}}
<
make "lower_a ascii "a
make "lower_z ascii "z
Line 4,076:
print sentence "|Encrypted:| :ciphertext
print sentence "|Recovered:| :recovered
bye</
{{out}}
Line 4,085:
=={{header|Lua}}==
<
return text:gsub("%a", function(t)
local base = (t:lower() == t and string.byte('a') or string.byte('A'))
Line 4,115:
print("Decrypted text: ", decrypted)
end
</syntaxhighlight>
'''Fast version'''
<
local function make_table(k)
Line 4,150:
end
return string.char(unpack(res_t))
end</
=={{header|M2000 Interpreter}}==
We use a Buffer object (is a pointer type to a block of memory), to store string, to have access using unsigned integers.
<
a$="THIS IS MY TEXT TO ENCODE WITH CAESAR CIPHER"
Function Cipher$(a$, N) {
Line 4,173:
Print Cipher$(B$,12)
</syntaxhighlight>
=={{header|Maple}}==
<
> StringTools:-Encode( "The five boxing wizards jump quickly", encoding = alpharot[3] );
"Wkh ilyh eralqj zlcdugv mxps txlfnob"
Line 4,182:
> StringTools:-Encode( %, encoding = alpharot[ 23 ] );
"The five boxing wizards jump quickly"
</syntaxhighlight>
(The symbol % refers the the last (non-NULL) value computed.)
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
{{out}}
<pre>cypher["The five boxing wizards jump quickly",3]
Line 4,192:
=={{header|MATLAB}} / {{header|Octave}}==
<
s = char( mod(s - 'A' + key, 25 ) + 'A');
end;
function s = decipherCaesar(s, key)
s = char( mod(s - 'A' - key, 25 ) + 'A');
end; </
Here is a test:
<
ans = ABC </
=={{header|Microsoft Small Basic}}==
<
TextWindow.Write("Enter a 1-25 number key (-ve number to decode): ")
key = TextWindow.ReadNumber()
Line 4,227:
TextWindow.WriteLine(message)
TextWindow.WriteLine(caeser)
</syntaxhighlight>
{{out}}
<pre>Enter a 1-25 number key (-ve number to decode): 10
Line 4,243:
=={{header|MiniScript}}==
<
chars = s.values
for i in chars.indexes
Line 4,254:
print caesar("Hello world!", 7)
print caesar("Olssv dvysk!", 26-7)</
{{out}}
Line 4,263:
==={{header|mLite}}===
In this implementation, the offset can be positive or negative and is wrapped around if greater than 25 or less than -25.
<
| x = let val ln = readln ()
in if eof ln then
Line 4,303:
;
map println ` map (fn s = encipher (s,ston ` default (argv 0, "1"))) ` readfile ();
</syntaxhighlight>
The string for encoding is supplied as an input stream, and the offset supplied on the command line (defaults to 1). For example
<pre>echo The cat sat on the mat | mlite -f caecip.m ~5</pre>
Line 4,311:
=={{header|Modula-2}}==
{{trans|Java}}
<
FROM Conversions IMPORT IntToStr;
FROM Terminal IMPORT WriteString, WriteLn, ReadChar;
Line 4,387:
ReadChar;
END CaesarCipher.</
=={{header|Modula-3}}==
Line 4,396:
It also illustrates the use of exceptions in Modula-3.
<
IMPORT IO, IntSeq, Text;
Line 4,481:
Decode(buffer, message);
IO.Put(message); IO.PutChar('\n');
END Caesar.</
{{out}}
Line 4,490:
=={{header|Nanoquery}}==
<
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercase = "abcdefghijklmnopqrstuvwxyz"
Line 4,524:
return plaintext
end</
=={{header|NetRexx}}==
The cipher code in this sample is also used in the [[Rot-13#NetRexx|Rot-13 – NetRexx]] task.
<
options replace format comments java crossref savelog symbols nobinary
Line 4,619:
method isFalse public static returns boolean
return \isTrue</
<pre style="height: 60ex; overflow: scroll;">
Line 4,715:
=={{header|Nim}}==
{{trans|Python}}
<
proc caesar(s: string, k: int, decode = false): string =
Line 4,728:
let enc = caesar(msg, 11)
echo enc
echo caesar(enc, 11, decode = true)</
=={{header|Oberon-2}}==
Works with oo2c version2
<
MODULE Caesar;
IMPORT
Line 4,792:
END Caesar.
</syntaxhighlight>
Output:
<pre>
Line 4,801:
=={{header|Objeck}}==
<
class Caesar {
function : native : Encode(enc : String, offset : Int) ~ String {
Line 4,831:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 4,839:
=={{header|OCaml}}==
<
c >= 'a' && c <= 'z'
Line 4,863:
else
c
) str</
<
let key = 3 in
let orig = "The five boxing wizards jump quickly" in
Line 4,872:
print_endline deciphered;
Printf.printf "equal: %b\n" (orig = deciphered)
;;</
{{out}}
<pre>$ ocaml caesar.ml
Line 4,881:
=={{header|Oforth}}==
<
c dup isLetter ifFalse: [ return ]
isUpper ifTrue: [ 'A' ] else: [ 'a' ] c key + over - 26 mod + ;
: cipherE(s, key) s map(#[ key ceasar ]) charsAsString ;
: cipherD(s, key) cipherE(s, 26 key - ) ;</
{{out}}
Line 4,898:
=={{header|OOC}}==
<
shift := args[1] toInt()
if (args length != 3) {
Line 4,916:
str println()
}
}</
{{out}}
<pre>$ ./caesar 8 "This should be a fairly original sentence."
Line 4,924:
=={{header|PARI/GP}}==
<
Strchr(Vecsmall(apply(k->if(k>96&&k<123,(k+n-97)%26+97, if(k>64&&k<91, (k+n-65)%26+65, k)),
Vec(Vecsmall(s)))))
};
dec(s,n)=enc(s,-n);</
=={{header|Pascal}}==
<
procedure encrypt(var message: string; key: integer);
Line 4,968:
writeln ('Decrypted message: ', message);
readln;
end.</
{{out}}
<pre>>: ./CaesarCipher
Line 4,978:
=={{header|Perl}}==
<
my ($message, $key, $decode) = @_;
$key = 26 - $key if $decode;
Line 4,989:
print "msg: $msg\nenc: $enc\ndec: $dec\n";
</syntaxhighlight>
{{out}}
Line 4,997:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">alpha_b</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">255</span><span style="color: #0000FF;">)</span>
Line 5,018:
<span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">caesar</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">caesar</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">26</span><span style="color: #0000FF;">-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">e</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">r</span>
<!--</
{{out}}
<pre>
Line 5,028:
=={{header|PHP}}==
<
function caesarEncode( $message, $key ){
$plaintext = strtolower( $message );
Line 5,046:
echo caesarEncode( "The quick brown fox Jumped over the lazy Dog", 12 ), "\n";
?></
{{out}}
<pre>ftq cguow ndaiz raj vgybqp ahqd ftq xmlk pas</pre>
Line 5,052:
Or, using PHP's '''strtr()''' built-in function
<
function caesarEncode($message, $key) {
Line 5,060:
}
echo caesarEncode('THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG', 12), PHP_EOL;</
{{out}}
Line 5,066:
=={{header|Picat}}==
<
S = "All human beings are born free and equal in dignity and rights.",
println(S),
Line 5,089:
M.put(Lower[I],Lower[II])
end.
</syntaxhighlight>
{{out}}
Line 5,098:
=={{header|PicoLisp}}==
<
(de caesar (Str Key)
(pack
(mapcar '((C) (cadr (nth (member C *Letters) Key)))
(chop (uppc Str)) ) ) )</
Test:
<pre>: (caesar "IBM" 25)
Line 5,117:
=={{header|Pike}}==
Pike has built in support for substitution cryptos in the Crypto module. It's possible to set the desired alphabet, but the default a-z matches the Caesar range.
<
string msg = "The quick brown fox jumped over the lazy dogs";
string msg_s2 = c->encrypt(msg);
Line 5,124:
string decoded = c->decrypt(msg_s11);
write("%s\n%s\n%s\n%s\n", msg, msg_s2, msg_s11, decoded);</
{{out}}
Line 5,135:
=={{header|PL/I}}==
<
declare cypher_string character (52) static initial
((2)'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
Line 5,154:
put skip list ('Decyphered text=', text);
end caesar;</
{{out}} with offset of 5:
<pre>
Line 5,163:
=={{header|PowerShell}}==
<
function Get-CaesarCipher
{
Line 5,237:
$OutText = $null
}
}</
Usage examples:
<pre>
Line 5,258:
{{Works with|SWI-Prolog}}
{{libheader|clpfd}}
<
caesar :-
Line 5,290:
% compute values of V1 and V2
label([A, V1, V2]).</
{{out}}
<pre> ?- caesar.
Line 5,301:
=={{header|PureBasic}}==
The case is maintained for alphabetic characters (uppercase/lowercase input = uppercase/lowercase output) while non-alphabetic characters, if present are included and left unchanged in the result.
<
;if reverse <> 0 then reverse the encryption (decrypt)
If reverse: reverse = 26: key = 26 - key: EndIf
Line 5,337:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
{{out}}
<pre> Plain text = "The quick brown fox jumped over the lazy dogs."
Line 5,344:
===Alternate solution===
Here is an alternate and more advanced form of the encrypt procedure. It improves on the simple version in terms of speed, in case Caesar is using the cipher on some very long documents. It is meant to replace the encrypt procedure in the previous code and produces identical results.
<
;if reverse <> 0 then reverse the encryption (decrypt)
Protected i, *letter.Character, *resultLetter.Character, result.s = Space(Len(text))
Line 5,364:
Wend
ProcedureReturn result
EndProcedure</
=={{header|Python}}==
<
if decode: k = 26 - k
return "".join([chr((ord(i) - 65 + k) % 26 + 65)
Line 5,377:
enc = caesar(msg, 11)
print enc
print caesar(enc, 11, decode = True)</
{{out}}
<pre>The quick brown fox jumped over the lazy dogs
Line 5,384:
Alternate solution
{{works with|Python|2.x}} (for 3.x change <code>string.maketrans</code> to <code>str.maketrans</code>)
<
def caesar(s, k, decode = False):
if decode: k = 26 - k
Line 5,398:
enc = caesar(msg, 11)
print enc
print caesar(enc, 11, decode = True)</
{{out}}
<pre>
Line 5,408:
Variant with memoization of translation tables
{{works with|Python|3.x}}
<
def caesar(s, k = 13, decode = False, *, memo={}):
if decode: k = 26 - k
Line 5,418:
string.ascii_uppercase[k:] + string.ascii_uppercase[:k] +
string.ascii_lowercase[k:] + string.ascii_lowercase[:k])
return s.translate(table)</
A compact alternative solution
<
from string import ascii_uppercase as abc
Line 5,431:
print(caesar(msg, 11))
print(caesar(caesar(msg, 11), 11, True))
</syntaxhighlight>
{{out}}
<pre>
Line 5,444:
{{works with|True BASIC}} Note that TrueBasic uses '!' for comments
{{trans|BASIC256}}
<
LET tipo$ = "cleartext "
Line 5,475:
END IF
NEXT i
END</
=={{header|Quackery}}==
<
[ dup lower != ] is upper? ( c --> b )
Line 5,510:
=={{header|R}}==
This is a generalization of the Rot-13 solution for R at: http://rosettacode.org/wiki/Rot-13#R .
<syntaxhighlight lang=R>
# based on Rot-13 solution: http://rosettacode.org/wiki/Rot-13#R
ceasar <- function(x, key)
Line 5,539:
</syntaxhighlight>
{{out}}
<pre>
Line 5,555:
=={{header|Racket}}==
<
#lang racket
Line 5,575:
(define (encrypt s) (caesar s 1))
(define (decrypt s) (caesar s -1))
</syntaxhighlight>
Example:
<pre>
Line 5,588:
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang=raku
sub encrypt ( $key where 1..25, $plaintext ) {
$plaintext.trans( @alpha Z=> @alpha.rotate($key) );
Line 5,602:
.say for $original, $en, $de;
say 'OK' if $original eq all( map { .&decrypt(.&encrypt($original)) }, 1..25 );</
{{out}}
<pre>THE FIVE BOXING WIZARDS JUMP QUICKLY
Line 5,610:
=={{header|Red}}==
<
Red ["Ceasar Cipher"]
Line 5,638:
encrypt: :caesar
decrypt: func spec-of :caesar [caesar src negate key]
</syntaxhighlight>
<pre>
>> print encrypt "Ceasar Cipher" 4
Line 5,649:
=={{header|Retro}}==
Retro provides a number of classical cyphers in the '''crypto'''' library. This implementation is from the library.
<
variable offset
: rotate ( cb-c ) tuck - @offset + 26 mod + ;
Line 5,662:
( Example )
"THEYBROKEOURCIPHEREVERYONECANREADTHIS" 3 ceaser ( returns encrypted string )
23 ceaser ( returns decrypted string )</
=={{header|REXX}}==
===only Latin letters===
This version conforms to the task's restrictions.
<
/*──────────── or blanks allowed, all lowercase Latin letters are treated as uppercase.*/
parse arg key .; arg . p /*get key & uppercased text to be used.*/
Line 5,688:
return translate(s, substr(@ || @, ky, L), @) /*return the processed text.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say '***error***'; say; say arg(1); say; exit 13</
{{out|output|text= when using the input of: <tt> 22 The definition of a trivial program is one that has no bugs </tt>}}
<pre>
Line 5,700:
This version allows upper and lowercase Latin alphabet as well as all the
characters on the standard (computer) keyboard including blanks.
<
parse arg key p /*get key and the text to be cyphered. */
say 'Caesar cypher key:' key /*echo the Caesar cypher key to console*/
Line 5,721:
return translate(s, substr(@ || @, ky, L), @) /*return the processed text.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say '***error***'; say; say arg(1); say; exit 13</
{{out|output|text= when using the input of: <tt> 31 Batman's hood is called a "cowl" (old meaning). </tt>}}
<pre>
Line 5,731:
=={{header|Ring}}==
<
# Project : Caesar cipher
Line 5,789:
next
return str
</syntaxhighlight>
Output:
<pre>
Line 5,805:
=={{header|Ruby}}==
<
ALFABET = ("A".."Z").to_a
Line 5,817:
encypted = "THEYBROKEOURCIPHEREVERYONECANREADTHIS".caesar_cipher(3)
decrypted = encypted.caesar_cipher(-3)
</syntaxhighlight>
=={{header|Run BASIC}}==
<
a$ = "Pack my box with five dozen liquor jugs"
Line 5,840:
cipher$ = cipher$;code$
next i
END FUNCTION</
{{out}}
<pre>Gimme a ofset:?9
Line 5,849:
=={{header|Rust}}==
This example shows proper error handling. It skips non-ASCII characters.
<
use std::fmt::Display;
use std::{env, process};
Line 5,884:
let _ = writeln!(&mut io::stderr(), "ERROR: {}", msg);
process::exit(code);
}</
=={{header|Scala}}==
<
private val alphaU='A' to 'Z'
private val alphaL='a' to 'z'
Line 5,898:
def decode(text:String, key:Int)=encode(text,-key)
private def rot(a:IndexedSeq[Char], c:Char, key:Int)=a((c-a.head+key+a.size)%a.size)
}</
<
println("Plaintext => " + text)
val encoded=Caesar.encode(text, 3)
println("Ciphertext => " + encoded)
println("Decrypted => " + Caesar.decode(encoded, 3))</
{{out}}
<pre>Plaintext => The five boxing wizards jump quickly
Line 5,912:
This version first creates non shifted and shifted character sequences
and then encodes and decodes by indexing between those sequences.
<
@annotation.tailrec
private def rotate(p: Int, s: IndexedSeq[Char]): IndexedSeq[Char] = if (p < 0) rotate(s.length + p, s) else s.drop(p) ++ s.take(p)
Line 5,923:
def encode(c: Char) = if (as.contains(c)) bs(as.indexOf(c)) else c
def decode(c: Char) = if (bs.contains(c)) as(bs.indexOf(c)) else c
}</
<
val myCaeser = new Caeser(3)
val encoded = text.map(c => myCaeser.encode(c))
println("Plaintext => " + text)
println("Ciphertext => " + encoded)
println("Decrypted => " + encoded.map(c => myCaeser.decode(c)))</
{{out}}
Line 5,939:
=={{header|Scheme}}==
<
; Works with R7RS-compatible Schemes (e.g. Chibi).
; Also current versions of Chicken, Gauche and Kawa.
Line 5,966:
(display (string-map caesar msg))
(newline)
</syntaxhighlight>
{{out}}
Line 5,975:
=={{header|sed}}==
This code is roughly equivalent to the [[Rot-13#sed|rot-13]] cypher sed implementation, except that the conversion table is parameterized by a number and that the conversion done manually, instead of using `y///' command.
<
# Input: <number 0..25>\ntext to encode
Line 6,011:
/\n\n/! s/\n([^\n])/\1\n/
t loop
s/\n\n.*//</
{{out}}
<pre>
Line 6,026:
=={{header|Seed7}}==
<
const func string: rot (in string: stri, in integer: encodingKey) is func
Line 6,054:
writeln("Encrypted: " <& rot(testText, exampleKey));
writeln("Decrypted: " <& rot(rot(testText, exampleKey), 26 - exampleKey));
end func;</
{{out}}
<pre>
Line 6,064:
=={{header|SequenceL}}==
You only have to write an encrypt and decrypt function for characters. The semantics of Normalize Transpose allow those functions to be applied to strings.
<
import <Utilities/Conversion.sl>;
Line 6,095:
"Input: \t" ++ args[1] ++ "\n" ++
"Encrypted:\t" ++ encrypted ++ "\n" ++
"Decrypted:\t" ++ decrypted;</
{{out}}
<pre>
Line 6,106:
=={{header|Sidef}}==
{{trans|Perl}}
<
decode && (key = (26 - key));
msg.gsub(/([A-Z])/i, {|c| ((c.uc.ord - 65 + key) % 26) + 65 -> chr});
Line 6,118:
say "msg: #{msg}";
say "enc: #{enc}";
say "dec: #{dec}";</
{{out}}
Line 6,129:
=={{header|Sinclair ZX81 BASIC}}==
Works with 1k of RAM. A negative key decodes.
<
20 INPUT T$
30 LET C$=""
Line 6,140:
100 LET C$=C$+L$
110 NEXT I
120 PRINT C$</
{{in}}
<pre>12
Line 6,156:
{{works with|Smalltalk/X}}
well, I'm lucky: the standard library already contains a rot:n method!
<
but if it wasn't, here is an implementation for other smalltalks:
<
!CharacterArray methodsFor:'encoding'!
rot:n
Line 6,178:
^ self
</syntaxhighlight>
=={{header|SSEM}}==
Line 6,186:
This is in fact a general solution that will work equally well with alphabets of more or fewer than 26 characters: simply replace the constant 26 in storage address 18 with 22 for Hebrew, 24 for Greek, 28 for Arabic, 33 for Russian, etc.
<
11001000000000010000000000000000 1. Sub. 19
10101000000001100000000000000000 2. c to 21
Line 6,204:
00000000000001110000000000000000 16. Stop
11010000000000000000000000000000 17. 11
01011000000000000000000000000000 18. 26</
=={{header|Stata}}==
<
u = ascii(s)
i = selectindex(u:>=65 :& u:<=90)
Line 6,218:
caesar("layout", 20)
fusion</
=={{header|Swift}}==
<
func usage(_ e:String) {
print("error: \(e)")
Line 6,304:
test()
main()
</syntaxhighlight>
=={{header|Tcl}}==
<
oo::class create Caesar {
Line 6,329:
string map $decryptMap $text
}
}</
Demonstrating:
<
set txt "The five boxing wizards jump quickly."
set enc [$caesar encrypt $txt]
Line 6,337:
puts "Original message = $txt"
puts "Encrypted message = $enc"
puts "Decrypted message = $dec"</
{{out}}
<pre>
Line 6,346:
=={{header|TUSCRIPT}}==
<
text="THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
PRINT "text orginal ",text
Line 6,369:
DECODED = EXCHANGE (encoded,secret2abc)
PRINT "encoded decoded ",decoded</
{{out}}
<pre>
Line 6,379:
=={{header|TXR}}==
The strategy here, one of many possible ones, is to build, at run time,the arguments to be passed to deffilter to construct a pair of filters <code>enc</code> and <code>dec</code> for encoding and decoding. Filters are specified as tuples of strings.
<
@(cases)
@{key /[0-9]+/}
Line 6,401:
encoded: @{text :filter enc}
decoded: @{text :filter dec}
@(end)</
{{out}}
<pre>$ ./txr caesar.txr 12 'Hello, world!'
Line 6,412:
=={{header|TypeScript}}==
<
return input.replace(/([a-z])/g,
($1) => String.fromCharCode(($1.charCodeAt(0) + key + 26 - 97) % 26 + 97)
Line 6,425:
console.log('Enciphered: ' + encoded);
console.log('Deciphered: ' + decoded);</
=={{header|UNIX Shell}}==
{{works with|bash}}
I added a <tt>tr</tt> function to make this "pure" bash. In practice, you'd remove that function and use the external <tt>tr</tt> utility.
<
local OPTIND
local encrypt n=0
Line 6,485:
echo "original: $txt"
echo "encrypted: $enc"
echo "decrypted: $dec"</
{{out}}
<pre>
Line 6,493:
=={{header|Ursa}}==
<
while (not (or (= mode "encode") (= mode "decode")))
out "encode/decode: " console
Line 6,520:
end if
end for
out endl console</
=={{header|Ursala}}==
The reification operator (<code>-:</code>) generates efficient code for applications like this given a table of inputs and outputs, which is obtained in this case by zipping the alphabet with itself rolled the right number of times, done separately for the upper and lower case letters and then combined.
<
#import nat
Line 6,534:
#show+ # exhaustive test
test = ("n". <.enc"n",dec"n"+ enc"n"> plaintext)*= nrange/1 25</
{{out}}
<pre style="overflow: auto; height: 6em;">
Line 6,590:
=={{header|Vala}}==
This is a port of the C# code present in this page.
<
stdout.printf("%s\r\n", str);
}
Line 6,622:
println(encrypt(test_case, -1));
println(decrypt(encrypt(test_case, -1), -1));
}</
{{out}}
Line 6,633:
=={{header|VBA}}==
<syntaxhighlight lang=vb>
Option Explicit
Line 6,668:
Caesar_Cipher = strTemp
End Function
</syntaxhighlight>
{{out}}
Line 6,676:
=={{header|VBScript}}==
Note that a left rotation has an equivalent right rotation so all rotations are converted to the equivalent right rotation prior to translation.
<
str = "IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES."
Line 6,712:
End Function
</syntaxhighlight>
{{out}}
<pre>
Line 6,723:
=={{header|Vedit macro language}}==
This implementation ciphers/deciphers a highlighted block of text in-place in current edit buffer.
<
Goto_Pos(Block_Begin)
Line 6,733:
Char(1)
}
}</
{{out}} with key 13:
Line 6,744:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Function Encrypt(ch As Char, code As Integer) As Char
Line 6,774:
End Sub
End Module</
{{out}}
<pre>Pack my box with five dozen liquor jugs.
Line 6,781:
=={{header|Wortel}}==
<
; this function only replaces letters and keeps case
ceasar &[s n] !!s.replace &"[a-z]"gi &[x] [
Line 6,798:
]
!!ceasar "abc $%^ ABC" 10
}</
Returns:
<pre>"klm $%^ KLM"</pre>
Line 6,804:
=={{header|Wren}}==
{{trans|Kotlin}}
<
static encrypt(s, key) {
var offset = key % 26
Line 6,829:
var encoded = Caesar.encrypt("Bright vixens jump; dozy fowl quack.", 8)
System.print(encoded)
System.print(Caesar.decrypt(encoded, 8))</
{{out}}
Line 6,840:
{{trans|C custom implementation}}
{{works with|GCC|7.3.0 - Ubuntu 18.04 64-bit}}
<
.intel_syntax noprefix
Line 6,941:
mov eax, 0 # 0
leave
ret # return 0</
Usage:
<
$ ./caesar 10 abc
klm
$ ./caesar 16 klm
abc</
=={{header|XBasic}}==
{{trans|Modula-2}}
{{works with|Windows XBasic}}
<
PROGRAM "caesarcipher"
VERSION "0.0001"
Line 7,009:
END FUNCTION e$
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 7,018:
=={{header|XBS}}==
<
func caesar(text,shift:number=1){
Line 7,054:
log(e);
log(d);</
{{out}}
<pre>
Line 7,062:
=={{header|XLISP}}==
<
(defun encode (ascii-code)
(defun rotate (character alphabet)
Line 7,077:
(defun caesar-decode (text key)
(caesar-encode text (- 26 key)))</
Test it in a REPL:
<
CAESAR-TEST
Line 7,087:
[3] (caesar-decode caesar-test 14)
"CAESAR: Who is it in the press that calls on me? I hear a tongue, shriller than all the music, Cry 'Caesar!' Speak; Caesar is turn'd to hear."</
=={{header|XPL0}}==
Line 7,093:
Usage: caesar key <infile.txt >outfile.xxx
<
int Key, C;
[Key:= IntIn(8);
Line 7,105:
ChOut(0, C);
until C=$1A; \EOF
]</
Example outfile.xxx:
Line 7,113:
=={{header|Yabasic}}==
<
REM *** By changing the key and pattern, an encryption system that is difficult to break can be achieved. ***
Line 7,148:
return res$
end sub</
{{out}}
<pre>You are encouraged to solve this task according to the task description, using any language you may know.
Line 7,157:
=={{header|zkl}}==
<
var [const] letters=["a".."z"].chain(["A".."Z"]).pump(String); // static
if(not encode) n=26 - n;
Line 7,163:
ltrs:=String(letters[n,sz],letters[0,n],letters[m,sz],letters[26,n]);
str.translate(letters,ltrs)
}</
<
N:=3;
code:=caesarCodec(text,N);
println("text = ",text);
println("encoded(%d) = %s".fmt(N,code));
println("decoded = ",caesarCodec(code,N,False));</
{{out}}
<pre>
Line 7,178:
=={{header|zonnon}}==
<
module Caesar;
const
Line 7,236:
writeln(txt," -c-> ",cipher," -d-> ",decipher)
end Caesar.
</syntaxhighlight>
{{Out}}
<pre>
Line 7,246:
=={{header|ZX Spectrum Basic}}==
{{trans|BBC BASIC}}
<
20 PRINT t$''
30 LET key=RND*25+1
Line 7,259:
1050 NEXT i
1060 RETURN
</syntaxhighlight>
{{trans|Yabasic}}
<
20 LET c$="a":REM more characters, more difficult for decript
30 LET CIFRA=1: LET DESCIFRA=-1
Line 7,290:
1170 LET r$=r$+p$(delta)
1180 NEXT i
1190 RETURN </
{{omit from|GUISS}}
|