Page 1 of 1

[Source] Morse Code Functions (x64)

Posted: Sat Jul 12, 2025 9:36 pm
by Mijikai
Some functions i wrote while playing around with morse codes.

Source (x64):

Code: Select all

EnableExplicit

; MORSE CODE FUNCTIONS
; Version: draft
; PureBasic 6.21 (x64)
; Copyright (c) 2025 Mijikai
; MIT License

Structure _MORSE_CODE
  id.a
  length.a
  byte.a[4]
  char.s{1}
EndStructure

; Procedure.i morse_code_pack(id.i,length.i,code_0.i,code_1.i,code_2.i,code_3.i,code_4.i,code_5.i,code_6.i,code_7.i)
;   Protected._MORSE_CODE *code
;   Protected.i result
;   *code = @result
;   *code\id = id
;   *code\length = length
;   *code\byte[0] = (((code_1 & $F) << 4) | (code_0 & $F))
;   *code\byte[1] = (((code_3 & $F) << 4) | (code_2 & $F))
;   *code\byte[2] = (((code_5 & $F) << 4) | (code_4 & $F))
;   *code\byte[3] = (((code_7 & $F) << 4) | (code_6 & $F))
;   *code\char = Chr(id)
;   ProcedureReturn result
; EndProcedure

Procedure.s morse_code_unpack(*code._MORSE_CODE);<- unpack morse string
  Protected.i length,index,count
  Protected.i type,check,offset
  Protected.s result
  Protected.Character *append
  result = Space(14)
  *append = @result
  For length = 1 To *code\length
    type = (*code\byte[index] >> (4 * count)) & $F
    check = type % 2
    type = (type - check) >> 1
    For offset = 0 To type
      *append\c = 46 - check
      *append + SizeOf(Character)
    Next
    index + count
    count ! 1
  Next
  ProcedureReturn Trim(result)
EndProcedure

Procedure.s morse_encode_text(text.s)
  Protected.Ascii *char
  Protected._MORSE_CODE *code
  Protected.i match
  Protected.s result
  *char = @text
  While *char\a
    *code = ?morse_table
    For match = 0 To 51
      If *char\a = *code\id
        result + morse_code_unpack(*code)
        Break
      EndIf
      *code + 8
    Next
    *char + 2
  Wend
  ProcedureReturn result
EndProcedure

Procedure.i main()
  Debug morse_encode_text("hello world 1234567890");<- text needs to be in lowercase
EndProcedure

End main()

DataSection
  morse_table:
  Data.i $61000000100261,$62000000410262,$63000001010463,$64000000210264
  Data.i $65000000000165,$66000000120366,$67000000030267,$68000000060168
  Data.i $69000000020169,$6A00000050026A,$6B00000101036B,$6C00000210036C
  Data.i $6D00000003016D,$6E00000001026E,$6F00000005016F,$70000000300370
  Data.i $71000001030371,$72000000100372,$73000000040173,$74000000010174
  Data.i $75000000120275,$76000000140276,$77000000300277,$78000001210378
  Data.i $79000003010379,$7A00000023027A,$30000000090130,$31000000700231
  Data.i $32000000520232,$33000000340233,$34000000160234,$35000000080135
  Data.i $36000000610236,$37000000430237,$38000000250238,$39000000070239
  Data.i $26000004100326,$27000000700327,$40000010300540,$29000103010529
  Data.i $28000003010428,$3A00000045023A,$2C00000323032C,$3D00000141033D
  Data.i $21000301010521,$2E00101010062E,$2D00000161032D,$2A00000121032A
  Data.i $2B00001010052B,$22000012100522,$3F00000232033F,$2F00000121042F
EndDataSection