Convert Integer Values to Packed Strings (Bin$() replacement)

Started by kevin, March 08, 2008, 02:21:48 PM

Previous topic - Next topic

kevin


PackedBin - Bin$() replacement

  This snippet returns a  binary representation of the passed value in string form.  So it's provides same base functionality as the Bin$() function, but with one primary difference.  This version removes leading zeros..


PlayBASIC Code: [Select]
 For lp=0 to 256 step 10
print "Bin$()="+Bin$(lp)+" Packed Bin="+PackedBin(lp)
next

Sync
waitkey



Function PackedBin(ThisValue)
s$=Bin$(ThisValue)
pos=Instring(s$,"1",1,false)
if Pos
s$="%"+Right$(s$,len(s$)-(pos-1))
else
s$="%0"
endif
EndFunction s$








kevin


Trimmed Bin$ and HEX$ function

     Here's a couple of alternative BIN$ and HEX$ functions that return results to in groups of 8 bits. 



PlayBASIC Code: [Select]
   for lp =0 to 10

Thisvalue=rnd(255)*$10000

print bin$(Thisvalue)
print TrimmedBin$(ThisValue)

print Hex$(Thisvalue)
print TrimmedHex$(ThisValue)

next

Sync
waitkey



Psub TrimmedBin$(ThisValue)

if ThisValue & $ff000000
result$=bin$(Thisvalue)

elseif ThisValue & $00ff0000
result$="%"+right$(bin$(Thisvalue),24)

elseif ThisValue & $0000ff00
result$="%"+right$(bin$(Thisvalue),16)

else
result$="%"+right$(bin$(Thisvalue),8)
endif

EndPsub result$


Psub TrimmedHex$(ThisValue)

if ThisValue & $ff000000
result$=hex$(Thisvalue)

elseif ThisValue & $00ff0000
result$="$"+right$(hex$(Thisvalue),6)

elseif ThisValue & $0000ff00
result$="$"+right$(hex$(Thisvalue),4)

else
result$="$"+right$(hex$(Thisvalue),2)
endif

EndPsub result$