Morse Code

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Dave Sinkula Dave Sinkula is offline Offline Nov 20th, 2005, 3:36 pm |
0
This code uses a structure to map a letter to an equivalent representation of Morse code. It simply loops through either a string to encode or decode looking for text to substitute with a replacement string or character. Output is presented to the stdout.
Quick reply to this message  
C Syntax
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4.  
  5. static const struct
  6. {
  7. const char letter, *morse;
  8. } Code[] =
  9. {
  10. { 'A', ".- " },{ 'B', "-... " },{ 'C', "-.-. " },{ 'D', "-.. " },
  11. { 'E', ". " },{ 'F', "..-. " },{ 'G', "--. " },{ 'H', ".... " },
  12. { 'I', ".. " },{ 'J', ".--- " },{ 'K', ".-.- " },{ 'L', ".-.. " },
  13. { 'M', "-- " },{ 'N', "-. " },{ 'O', "--- " },{ 'P', ".--. " },
  14. { 'Q', "--.- " },{ 'R', ".-. " },{ 'S', "... " },{ 'T', "- " },
  15. { 'U', "..- " },{ 'V', "...- " },{ 'W', ".-- " },{ 'X', "-..- " },
  16. { 'Y', "-.-- " },{ 'Z', "--.. " },{ ' ', " " },
  17. };
  18.  
  19. void encode(const char *s)
  20. {
  21. size_t i, j;
  22. for ( i = 0; s[i]; ++i )
  23. {
  24. for ( j = 0; j < sizeof Code / sizeof *Code; ++j )
  25. {
  26. if ( toupper(s[i]) == Code[j].letter )
  27. {
  28. printf("%s", Code[j].morse);
  29. break;
  30. }
  31. }
  32. }
  33. putchar('\n');
  34. }
  35.  
  36. void decode(const char *morse)
  37. {
  38. size_t i, j;
  39. for ( i = 0; morse[i]; )
  40. {
  41. for ( j = 0; j < sizeof Code / sizeof *Code; ++j )
  42. {
  43. size_t size = strlen(Code[j].morse);
  44. if ( memcmp(Code[j].morse, &morse[i], size) == 0 )
  45. {
  46. putchar(Code[j].letter);
  47. i += size;
  48. break;
  49. }
  50. }
  51. }
  52. putchar('\n');
  53. }
  54.  
  55. int main(void)
  56. {
  57. const char text[] = "Hello world";
  58. const char test[] = ".... . .-.. .-.. --- .-- --- .-. .-.. -.. ";
  59. encode(text);
  60. decode(test);
  61. return 0;
  62. }
  63.  
  64. /* my output
  65. .... . .-.. .-.. --- .-- --- .-. .-.. -..
  66. HELLO WORLD
  67. */

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC