Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Morse decode using sed

This is a short Morse code decoder written as a shellscript using sed.

The Morse coded text should be in $text, and should be written with spaces between the letters.

echo $text\  | tr . 0 | sed -e {s/0----\ /1/g} -e {s/00---\ /2/g} -e {s/000--\ /3/g} -e {s/000-\ /4/g} -e {s/00000\ /5/g} -e {s/-0000\ /6/g} -e {s/--000\ /7/g} -e {s/---00\ /8/g} -e {s/----0\ /9/g} -e {s/-----\ /0/g} \
	| sed -e {s/-0-0\ /c/g} -e {s/-000\ /b/g} -e {s/00-0\ /f/g} -e {s/0000\ /h/g} -e {s/0---\ /j/g} -e {s/0-00\ /l/g} -e {s/0--0\ /p/g} -e {s/--0-\ /q/g} -e {s/000-\ /v/g} -e {s/-00-\ /x/g} -e {s/-0--\ /y/g} -e {s/--00\ /z/g} \
	| sed -e {s/0--\ /w/g} -e {s/-00\ /d/g} -e {s/--0\ /g/g} -e {s/-0-\ /k/g} -e {s/---\ /o/g} -e {s/0-0\ /r/g} -e {s/000\ /s/g} -e {s/00-\ /u/g} \
	| sed -e {s/0-\ /a/g} -e {s/00\ /i/g} -e {s/--\ /m/g} -e {s/-0\ /n/g} \
	| sed -e {s/0\ /e/g} -e {s/-\ /t/g}

Translates Morse code from a mobile phone style keypad into plain English

// Translates Morse code specially input from a Nokia 3510i or Nokia 6600 to plain English. I primarily used the button 1 for a dot, 2 for a dash and 5 for the terminator. I later extended the flexibility of the inputs by allowing 4 to be a dot, 7 a dash and 9 as the terminator. eg. ghi = dots pqrs = dashes wxyz = terminators and spaces.

#!/usr/bin/ruby
#filename: morsecode.rb

require 'net/http'
require 'rexml/document'

include REXML

class Morsecode
  def initialize
    @doc_mlookup = load_lookup('http://jamesrobertson.eu/p/xml/', 'morsecode.xml')
    @doc_charmcode = load_lookup('http://jamesrobertson.eu/p/xml/', 'charmcode.xml')
  end

  def load_lookup(url, filename)
    xml_data = Net::HTTP.get_response(URI.parse(url + filename)).body
    Document.new(xml_data)
  end

  def decode_string(doc, a_buffer)
    pstring = ''
    a_buffer.each do |word|
      pstring += doc.root.elements["code[@encode='" + word + "']"].text
    end
    pstring
  end

  def decode_kstring(buffer)
    decode_string(@doc_charmcode, buffer.scan(/./))
  end

  def decode_mstring(buffer)
    decode_string(@doc_mlookup, buffer.split('4'))
  end

  def decode(buffer)
    decode_mstring(decode_kstring(buffer)) if buffer.length > 0
  end
end

#test
a = Morsecode.new
puts a.decode('gwpwrwgw')


« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS