PERL Unpack
Posted: Wed Mar 28, 2012 7:27 pm
PERL has an unpack command that unpacks packed strings. Is there a way to implement that in PureBasic?
Code: Select all
; the "pack"
Procedure.s BinaryToText(bin_in$)
Protected out_txt_bin$, Ch$, unkvar.i
out_txt_bin$=""
For countx = 1 To Len(bin_in$) / 8
Ch$ = Mid(bin_in$, 8*(countx-1)+1 ,8)
unkvar=0
For countz = 1 To 8
Select Mid(Ch$, countz,1)
Case "0" : unkvar = 2 * unkvar
Case "1" : unkvar = 2 * unkvar+1
EndSelect
Next countz
out_txt_bin$ = out_txt_bin$ + Chr(unkvar)
Next countx
ProcedureReturn out_txt_bin$
EndProcedure
; the 'un-pack'
Procedure.s CharToBin(chrbin.s)
Protected outbin.s, chr_asc.i, TotCharAsc.i
outbin = ""
chr_asc = 0
TotCharAsc = 0
chr_asc = Asc(chrbin)
For countz = 7 To 0 Step -1
If chr_asc >= TotCharAsc + Pow(2, countz)
TotCharAsc = TotCharAsc + Pow(2, countz)
outbin = outbin + "1"
Else
outbin = outbin + "0"
EndIf
Next
ProcedureReturn outbin
EndProcedure
Procedure.s TextToBinary(str2bin.s)
Protected binout.s
binout = ""
For countx = 1 To Len(str2bin)
binout = binout + CharToBin(Mid(str2bin, countx, 1))
Next
ProcedureReturn binout
EndProcedure
xx$ = "Be sure to drink your milk."
Debug "Our text we will convert > " + xx$
; convert the text to binary - 'pack' ????
bin$ = TextToBinary(xx$)
; the binary
Debug "The binary > " + bin$ ; our binary string - 'pack' ??
; converting binary back to text and reading our original text to verify - 'un-pack' ????
Debug "Our original text convert from binary back to text > " + BinaryToText(bin$)