FreeBasic增强版任意变量数据转二进制

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

三、输出结果:

 总结:

自定义函数无需知道数据类型,只要传入数据地址及长度,就可以返回其对应的二进制值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值