FreeBasic内置的BIN()函数,只支持系统内置变量转换二进制,如果打算将一个自定义的结构体变量输出为二进制格式,则无法实现。
为此为实现这个需求,本人编写了一个任意变量类型转二进制的函数。
一、代码如下:
'===================================================
' 字符顺序反转
'===================================================
function StrReverse( byref s as string ) as string
dim v as string
dim i as integer
for i=len(s)-1 to 0 step -1
v = v + chr(s[i])
next i
function = v
end function
'===================================================
' 任意变量转二进制
'===================================================
function VarToBin( byval pbuf as any ptr, byval length as ubyte ) as string
dim i as integer
dim s as string
dim vs as string
dim p as ubyte ptr
dim value as ubyte
dim bi as ubyte
vs = ""
p = cptr ( ubyte ptr, pbuf )
for i = 1 to length
s = ""
value = p [ i-1 ]
while value>0
bi = ( value mod 2 )
value = fix( value / 2 )
s = s + str( bi )
wend
s = StrReverse( s )
dim sout as string = "00000000"
mid( sout, 8-len(s)+1, len(s) ) = s
vs = sout + vs
next i
function = vs
end function
二、函数调用:
Declare Sub MsgBox(ByRef lpText as string)
Declare function VarToBin( byval pbuf as any ptr, byval length as ubyte ) as string
Declare function StrReverse( byref s as string) as string
type uquad
high as uinteger
low as uinteger
end type
' ----------------------------------------------------------------------------------------
' main
' ----------------------------------------------------------------------------------------
function FBMAIN( byval hInstance as HINSTANCE,
byval hPrevInstance as HINSTANCE,
byref szCmdLine as string,
byval nCmdShow as long ) as long
dim a as uquad
dim b as ulongint = 12345687878
memcpy @a, @b, sizeof(b)
MsgBox "系统内置函数:" + LRCF +
bin( b, sizeof(b)*8 ) + LRCF +
"自定义函数:"+ LRCF +
VarToBin( @a, sizeof(a) )
function = 0
end function
三、输出结果:
总结:
自定义函数无需知道数据类型,只要传入数据地址及长度,就可以返回其对应的二进制值。