# Encode the alphabet cipher

Given a string that contains only lowercase letters, encode that string with the alphabet cipher.

To encode with the alphabet cipher (I will be using the example hello):

1. First, convert each letter in the string to a number depending on its position in the alphabet (a = 1, b = 2, etc.) Example: 8 5 12 12 15
2. Pad each number to two characters with 0s. Example: 08 05 12 12 15
3. Join. Example: 0805121215

## Test cases

helloworld -> 08051212152315181204
codegolf -> 0315040507151206
alphabetcipher -> 0112160801020520030916080518
johncena -> 1015081403051401


Remember, this is , so the code with the fewest number of bytes wins.

• Related. Commented Oct 28, 2016 at 17:09

# 05AB1E, 11 6 bytes

Code:

Ç4+€¦J


Explanation:

First, we convert the string to their ASCII values. codegolf would become:

[99, 111, 100, 101, 103, 111, 108, 102]


To get to the indices of the alphabet, you subtract 96:

[3, 15, 4, 5, 7, 15, 12, 6]


To pad with zeros, add 100 to each element and remove the first character of each int. For the above example, +100 would be:

[103, 115, 104, 105, 107, 115, 112, 106]


And removing the first character of each would lead to:

[03, 15, 04, 05, 07, 15, 12, 06]


We can merge both steps above (the -96 and the +100) part to just +4. For the code:

Ç       # Convert to an array of ASCII code points
4+     # Add four to each element in the array
€¦   # Remove the first character of each element
J  # Join to a single string


Try it online!

• What does ¦ do again? Commented Oct 28, 2016 at 17:33
• @carusocomputing Removes the first element of a string, list, etc. Commented Oct 28, 2016 at 17:34
• Beyond genius... Commented Oct 28, 2016 at 17:38

# Python 2, 42 bytes

f=lambda s:s andord(s[0])+4[1:]+f(s[1:])


Test it on Ideone.

• Non recursive, same byte count: lambda s:''.join(ord(x)+4[1:]for x in s) Commented Oct 28, 2016 at 18:00

# C, 55 43 bytes

f(char*c){for(;*c;)printf("%02d",*c++-96);}


ideone

• printf("%02d",*c++-96);} is shorter and valid if I'm not mistaken.
Commented Oct 28, 2016 at 17:42

# Pyth, 11 10 bytes

FNwpt+4CN


Try it! My first go at Pyth.

FNwpt+4CN
FNw         # For N in w (w is input, N will be single char)
p        # Print without newline
CN  # Int with code point N
+4CN  # Add 4 to int with code point N
+4CN  # representation of above (basically to string)
t+4CN  # Tail (All but first character)


Python equivalent:

for N in input():
print(repr(ord(N) + 4)[1:], end='')

• Good job on your first Pyth program! Commented Oct 28, 2016 at 19:04

# Python, 46 bytes

lambda x:"".join("%02i"%(ord(j)-96)for j in x)


Pretty straightforward. Try it on repl.it!

• Wow, two completely different attempts with the same byte count ;)
Commented Oct 28, 2016 at 17:19

# Jelly, 9 7 bytes

O+4ṾḊ$€  TryItOnline ### How? O+4ṾḊ$€ - Main link: s                                e.g. hello
O       - cast to ordinals                            e.g. [ 104,  101,  108,  108,  111]
+4     - add 4                                       e.g. [  108,  109,  112,  112,  115]
$€ - last two links as a monad for €ach Ṿ - uneval, effectively converts to strings e.g. ["108","109","112","112","115"] Ḋ - dequeue, remove the leading '1' e.g. [ "08", "09", "12", "12", "15"] - implicit print e.g. "0809121215"  • I came up with O+4DḊ€FṾ€ for the same count, perhaps golfable Commented Oct 28, 2016 at 17:39 • @ETHproductions O+4Ṿ€Ḋ€ saves 2 bytes. Commented Oct 28, 2016 at 17:40 • @Dennis I just did the same (ish)... Commented Oct 28, 2016 at 17:41 # Haskell, fortyfour 30 28 bytes (>>=tail.show.(+4).fromEnum)  Using the +4 approach from Adnan's answer saves 14 bytes. Try it on Ideone. Usage: > (>>=tail.show.(+4).fromEnum)"codegolf" "0315040507151206"  Two bytes off thanks to xnor. Old version: f a=['0'|a<'k']++(show$fromEnum a-96)
(f=<<)

• You don't need the second set of parens.
– xnor
Commented Oct 29, 2016 at 5:09

## Perl, 29 bytes

28 bytes of code + -n flag.

printf"%02s",-96+ord for/./g


Run with :

perl -ne 'printf"%02s",-96+ord for/./g' <<< "helloworld"

• 25 bytes (or 27 under the rules at the time of this challenge): Try it online! Commented Mar 26, 2020 at 20:14

# JavaScript (ES6), 52 49 bytes

f=s=>s&&(s.charCodeAt()+4+f(s.slice(1))).slice(1)


Recursion turned out to be 3 bytes shorter than .replace:

s=>s.replace(/./g,s=>(s.charCodeAt()+4+"").slice(1))


parseInt(s,36) is slightly longer for each approach, because you have to change 4 to 91:

s=>s.replace(/./g,s=>(parseInt(s,36)+91+"").slice(1))
f=s=>s&&(parseInt(s[0],36)+91+f(s.slice(1))).slice(1)


# Japt, 10 bytes

¡4+Xc)s s1


Probably doesn't get shorter than this...

Test it online!

## Explanation

¡           // Map each char X in the input by this function:
4+Xc)      //   Take 4 + the char code of X.
s s1  //   Convert to a string, then remove the first char.
// Implicit: output last expression


# Java 7,60 bytes

void f(char[]s){for(int i:s)System.out.printf("%02d",i-96);}

• This answer might not be valid because it takes a char[] instead of a String. Commented Oct 28, 2016 at 19:05
• Commented Oct 28, 2016 at 19:23
• @MartinEnder Okay. Thank you for the clarification. This answer has my upvote. Commented Oct 28, 2016 at 19:23

# MATL, 12 11 bytes

1 byte saved thanks to @Luis

4+!V4LZ)!le


Try it Online

# Hexagony, 33 bytes

10}{'a({=!{{\.@29$\,<.-":!\>Oct\%  Try it Online! Mm.. got a few no-ops in the Hexagon so I put today's date in. ## Expanded Form with date replaced by no-ops  1 0 } { ' a ( { = ! { { \ . @ . .$ \ , < .
- " : ! \ >
. . . \ %
. . . .

1. Initialise a 10 and move Memory Pointer to somewhere...
2. $ skips the mirror and , reads a byte. < branches: 3. If end of string (-1 which is non-positive) it goes to @ and terminates the program. 4. Otherwise it subtracts 95 (decremented a), and then we print result / 10 (integer division) and result % 10 and loop again. # Stax, 5 bytes öÇIªÆ  Run and debug it For each character • add 4 to the codepoint e.g. 108 • convert to string e.g. "108" • drop the first character e.g. "08" # APL (Dyalog Unicode), 19 12 bytes SBCS  ⎕UCS ⍝ Convert the argument (string) into an array of codepoints. 4+ ⍝ and add 4 to each of those codepoints. ¨ ⍝ Now, for each of those numbers ⍕ ⍝ turn it into a string ∘ ⍝ and 1↓ ⍝ drop its first character. ∊ ⍝ Finally enlist the strings into a single string (as in, join them together)  Thanks @Bubbler for saving 7 bytes ## my original 19 bytes {,/{1↓⍕⍵}¨4+⎕UCS ⍵}  Try it online! { } ⍝ Define a function taking a string as argument. ⎕UCS ⍵ ⍝ Convert the argument (string) into an array of codepoints. 4+ ⍝ and add 4 to each of those codepoints. { }¨ ⍝ For each number in the array, ⍕⍵ ⍝ convert it to a string 1↓ ⍝ and drop the first character (the 1). ,/ ⍝ Finally join everything and return.  • 12 bytes. Check out the successive transformations to shorten the code. Commented Mar 27, 2020 at 7:29 • @Bubbler thanks for the step-by-step! I'll read what those glyphs you introduced do, and then update my answer! – RGS Commented Mar 27, 2020 at 7:33 • @Bubbler If I understand correctly, ∊ is acting as some sort of "flatten" right? Because I have a list of strings, i.e. a list of lists of characters, and then the enlist operator turns everything into a 1d array? – RGS Commented Mar 27, 2020 at 19:33 # Vyxals, 6 bytes C4+ƛSḢ  -1 byte thanks to @Steffan Try it Online! Explanation: C # Convert to ASCII codes 4+ # Add 4 ƛ # On each number: S # Stringify Ḣ # Remove first char  • Try it Online! for 6 bytes. Commented Jul 29, 2022 at 3:35 • @Steffan Cool approach, thank you! Commented Jul 29, 2022 at 5:40 # Vim, 60 keystrokes :s/./\=char2nr(submatch(0))-96."\r"/g :%s/\<\d\n/0& V{gJ  An almost entirely regex based solution. As usual, using the eval register makes it obscenely long. # PHP, 58 Bytes foreach(str_split($argv[1])as$c)printf("%02d",ord($c)%32);

• you can -8 bytes iterating as a string 50 bytes TIO, or -11 bytes input via $argn 47 bytes TIO. Commented Aug 9, 2019 at 18:05 ## PowerShell v2+, 44 bytes -join([char[]]$args[0]|%{"{0:D2}"-f($_%32)})  Takes input $args[0], casts it as a char-array, feeds into a loop. Each iteration, we take the current character $_ modulo 32, which implicitly casts as the ASCII value. Conveniently ;-), this lines up so a = 1, b = 2, etc. That fed into the -format operator, operating on string "{0:D2}", which specifies a two digit minimum (i.e., it prepends a leading zero if required). Those strings of digits are encapsulated in parens, -joined together into one string, and left on the pipeline. Output via implicit Write-Output happens at program conclusion. PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'hello' 0805121215 PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'helloworld' 08051212152315181204 PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'codegolf' 0315040507151206 PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'johncena' 1015081403051401  # Perl, 24 bytes Includes +1 for -p Give input on STDIN: encode.pl <<< hello  encode.pl #!/usr/bin/perl -p s/./substr 4+ord$&,1/eg

• Nicely done. I think you probably meant 4+ord$& instead of 5+ord$& though ;-)
Commented Oct 30, 2016 at 8:35
• @Dada Right, pasted the version of my snippet buffer instead of the tested version again Commented Oct 30, 2016 at 18:31
• It happens! :) Could I ask you an unrelated question? Do you have any idea what is the 8 bytes perl solution to this question (reverse the input) (on anarchy) ?
Commented Oct 30, 2016 at 18:38
• @Dada I'd say it is impossible in pure perl, so I expect it's some abuse of the automated system on that side. E.g. if input came from STDIN you could do exec rev Commented Oct 31, 2016 at 7:12
• Right, that makes sense, thanks! I was having a hard time figuring this out since print is 5 bytes, <> is 2 more, so I was wondering what was the 1 byte builtin to reverse I hadn't heard of!
Commented Oct 31, 2016 at 9:48

# DASH, 27 bytes

@><""(->@rstr["."""]+4#0)#0


Example usage:

(@><""(->@rstr["."""]+4#0)#0)"helloworld"


# Explanation

@ (                         #. take input through a lambda
join "" (                 #. join with newlines the following:
(map                    #. result of mapping
@ (                   #. this lambda
rstr ["." ; ""] (     #. replace first char w/ empty string:
+ 4 #0               #. mapped item's codepoint + 4
)
)
) #0                    #. over the argument
)
)


## Batch, 256239 237 bytes

@echo off
set/ps=
set r=
set a=abcdefghijklmnopqrstuvwxyz
:g
set c=%a%
for /l %%i in (101,1,126)do call:l %%i
set s=%s:~1%
if not "%s%"=="" goto g
echo %r%
exit/b
:l
set i=%1
if %c:~,1%==%s:~,1% set r=%r%%i:~1%
set c=%c:~1%


Takes input on STDIN.

# IBM PC DOS 8088 Assembly, 3328 27 bytes

Assembled binary:

00000000: be82 00ac 2c60 7812 d40a 0530 3092 86f2  ....,x....00...
00000010: b402 cd21 86f2 cd21 ebe9 c3              ...!...!...


Unassembled:

BE 0082     MOV  SI, 82H        ; point SI to command line string
CH_LOOP:
AC          LODSB               ; load next char into AL
2C 60       SUB  AL, 'a'-1      ; convert ASCII to a=1,b=2...z=26
78 12       JS   DONE           ; if char is terminator or not valid, exit
D4 0A       AAM                 ; convert binary to BCD
05 3030     ADD  AX, '00'       ; convert BCD to ASCII
92          XCHG DX, AX         ; save AX to DX for display
86 F2       XCHG DH, DL         ; reverse bytes
B4 02       MOV  AH, 2          ; DOS display char function
CD 21       INT  21H            ; write first digit
86 F2       XCHG DH, DL         ; reverse bytes back
CD 21       INT  21H            ; write second digit
EB E9       JMP  CH_LOOP        ; restart loop
DONE:


Standalone PC DOS executable. Input string from command line, output to console.

I/O:

# BQN, 16 bytes

∾·(1↓•Fmt)¨4+-⟜@


Try it at BQN online!

### Explanation

Same approach, independently derived, as RGS's APL answer and tybocopperkettle's Vyxal s answer.

∾·(1↓•Fmt)¨4+-⟜@
-⟜@  Subtract null byte from each character, giving its ASCII value
4+      Add 4 (a = 101, z = 126)
(      )¨        Map this function to each number:
•Fmt            Format as string
1↓                Drop first character
∾·                Join together into a single string


# K (ngn/k), 8 bytes

,/1_'$4+  Try it online! 4+ add 4 to (the ASCII codes of) the argument - this turns a into 101, b into 102, etc $ format numbers as strings

1_' drop one digit from each

,/ concatenate

• Mind adding an explanation? Commented Jul 31, 2022 at 23:52
• done ⁩⁪⁫⁬⁭⁩⁪⁫⁬⁭⁩⁪⁫⁬⁭⁩⁪⁫⁬⁭⁩⁪⁫⁬⁭⁩⁪⁫⁬⁭⁩⁪⁫⁬⁭⁩⁪⁫⁬⁭⁩⁪⁫⁬⁭
– ngn
Commented Aug 2, 2022 at 3:07
• Oh that’s clever! Commented Aug 2, 2022 at 3:08
• not much different from other array-lang solutions, to be honest
– ngn
Commented Aug 2, 2022 at 3:10
• Just saved me 7 bytes ¯\_(ツ)_/¯ Commented Aug 2, 2022 at 4:05

# J, 25 22 15 bytes

[:,4}.@":@+3&u:


Try it online!

-7 bytes thanks to ngn's K approach

# Knight, 45 41 bytes

-4 thanks Aiden

;=xP W<1Lx;O++*'0'-2L=a-Ax 96a'\'=xSxF1""


Try it online!

• Instead of A GxF1 you can simply do Ax, because ASCII already returns the ascii value of the first character in the string. Commented Aug 14, 2022 at 23:11
• Nice trick using SxF1 instead of Gx 1Lx Commented Aug 15, 2022 at 16:17
• @Steffan SxF1"" and Gx 1Lx are the same bytecount and do the same thing, so it's just two different ways to do the same thing. Commented Aug 15, 2022 at 17:04
• Oh, for some reason I missed the "" lol Commented Aug 15, 2022 at 17:30

# Piet + ascii-piet, 44 bytes (2×22=44 codels)

tuuuumknnfbkqmkcalrmu_sajs?daltdddbfckkkkk ?


Try Piet online!

Input the string with the sentinel value _.

### Pseudocode

while true:
S = character input
n = (codepoint of S) - 96
if n+1 == 0:
exit
else:
print(floor(n/10))
print(n modulo 10)


# MATL, 11 bytes

96-OH&YA!1e


Try it online!

         % Implicit input
96-      % Subtract 96. So 'a' becomes 1, 'b' becomes 2 etc
OH&YA    % Convert each number to 2 decimal digits. Gives a 2-column matrix
!1e      % Transpose and linearize into a row
% Implicit display


## Ruby, 53 46 bytes

->s{s.chars.map{|c|(c.ord-96).to_s.rjust(2,?0)}.join}

->s{s.chars.map{|c|(c.ord+4).to_s[1..2]}.join}

• 41 bytes: ->s{s.chars.map{|c|"#{c.ord+4}"[1,2]}*''}` Commented Apr 24, 2020 at 11:08