morseencode.R (1313B)
1 #!/usr/bin/env Rscript 2 3 suppressPackageStartupMessages(library(dplyr)) 4 5 # Mapping from characters to morse code 6 morse_dat <- tibble::tribble( 7 ~char, ~morse, 8 "0", "-----", 9 "1", ".----", 10 "2", "..---", 11 "3", "...--", 12 "4", "....-", 13 "5", ".....", 14 "6", "-....", 15 "7", "--...", 16 "8", "---..", 17 "9", "----.", 18 "A", ".-", 19 "B", "-...", 20 "C", "-.-.", 21 "D", "-..", 22 "E", ".", 23 "F", "..-.", 24 "G", "--.", 25 "H", "....", 26 "I", "..", 27 "J", ".---", 28 "K", "-.-", 29 "L", ".-..", 30 "M", "--", 31 "N", "-.", 32 "O", "---", 33 "P", ".--.", 34 "Q", "--.-", 35 "R", ".-.", 36 "S", "...", 37 "T", "-", 38 "U", "..-", 39 "V", "...-", 40 "W", ".--", 41 "X", "-..-", 42 "Y", "-.--", 43 "Z", "--.." 44 ) 45 46 # Pack a Morse Code representation of a character into a short (16-bit) 47 # integer. `.` becomes `01`, `-` becomes `11`, signals are encoded with the 48 # early bits lower than later bits (they're "backwards". 49 encode_morse <- function(morse_sequence) { 50 sum(((strsplit(morse_sequence, "")[[1]] == "-") * 2 + 1) 51 * 4^(seq(0, nchar(morse_sequence)-1))) 52 } 53 54 morse_dat <- morse_dat |> 55 mutate(morse_int = as.integer(vapply(morse, encode_morse, double(1))), 56 morse_hex = sprintf('%0.4x', morse_int)) 57 58 cat(morse_dat$morse_hex, sep = '\n')