Created
December 27, 2017 16:06
-
-
Save adleroliveira/773e9bbb73b2745f1889db6dce5a9080 to your computer and use it in GitHub Desktop.
Message encoder: Morse, binary and hex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const encode = msg => { | |
const abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
const morsecode =[ | |
'.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', | |
'..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', | |
'--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', | |
'-.--', '--..' | |
] | |
const words = msg.toUpperCase().split(' ') | |
const encoder = w => w.split('').map(l => { | |
const idx = abc.indexOf(l) | |
if (idx === -1) throw new Error("Invalid characters in message") | |
return morsecode[idx] | |
}) | |
const encoded = words.map(encoder) | |
const chunk = (arr, size) => | |
Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size)) | |
const bitBuffer = [] | |
for (word of encoded) { | |
const wordBuffer = [] | |
for (letter of word) { | |
const beeps = [] | |
for (char of letter.split('')) { | |
if (char === '.') beeps.push('1') | |
else beeps.push('111') | |
} | |
wordBuffer.push(beeps.join('0')) | |
} | |
bitBuffer.push(wordBuffer.join('00')) | |
} | |
const binaryStr = bitBuffer.join('000') | |
const toHex = chunk(binaryStr, 8).map(b => { | |
const byte = b.length == 8 ? b : b + Array(9 - b.length).join("0") | |
return parseInt(byte, 2).toString(16) | |
}) | |
return toHex.join('') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment