- public function o2b(byval long nValue) as string
- dim nValueCopy as long
- dim nTmp as byte '商
- dim sReturn as string '返回值
- nValueCopy = nValue
- '也有用nValue - 2^N 方式的,这里就不多说了
- do while nValueCopy > 0
- nTmp = nValueCopy / 2
- sReturn = cstr( nValueCopy - nTmp / 2 ) & sReturn '反向累计
- nValueCopy = nTmp
- loop
- o2b = sReturn
- end function
- 而用c比较熟的人一般按位去做:
- public function o2b(byref long nValue) as string
- dim nBit( 0 to 7 ) as byte ' 最小的单位是byte了,放掩码
- dim nByte( 1 to 4 ) as byte ' 分解nValue到字节的
- dim nTmp as byte
- dim pValue as long ' 指针
- dim sReturn as string ' 返回值
- dim i as byte, j as byte
- nBit(0) = 1 '00000001
- nBit(1) = 2 '00000010
- nBit(2) = 4 '00000100
- nBit(3) = 8 '00001000
- nBit(4) = 16 '00010000
- nBit(5) = 32 '00100000
- nBit(6) = 64 '01000000
- nBit(7) = 128 '10000000
- ' 取 nValue 的地址
- pValue = VarPtr( nValue )
- ' win32 api, 将nValue的4个字节分别复制到nByte中,byref 就相当于指针
- CopyMemory( nByte(1), byref pValue, 4 )
- for i = 4 to 1 '低字节在前
- for j = 7 to 0 '高位开始
- ' 方法一, 减法
- nTmp = 0
- if nByte(i) > nBit(j) then
- nByte = nByte(i) - nBit(j)
- nTmp = 1 ' 这一位二进制是1
- end if
- sReturn = sReturn & cstr(nTmp)
- ' 方法二,按位与 效率更高
- nTmp = 1
- if ( not ( nByte(i) imp nBit(j) ) ) = nBit(j) then
- ' 我没有找到vb按位与的函数,只有按位"同与"(不记得是不是)的imp
- nTmp = 0
- end if
- sReturn = sReturn & cstr(nTmp)
- next j, i
- o2b = sReturn
- end function
- //该片段来自于http://www.codesnippet.cn/detail/090620133976.html
来源: http://www.codesnippet.cn/detail/090620133976.html