VB怎么将字串和二进制码互相转换

2024-11-22 18:46:14
推荐回答(3个)
回答1:

点击转换为二进制,再次点击转回来,注意只有一个command1和一个text1,你可以自己稍加修改改成你所需要的代码:
分别调用tobit和tostr函数就行,前者转字符串为二进制,后置相反

Dim isstr As Boolean ' 用作标记

Private Sub Command1_Click()
Dim s$
s = Text1.Text
If isstr Then ' isstr=true则表示文本框里为文本
Text1.Text = tobit(s) ' 执行文本->二进制转换
isstr = False
Else ' isstr=false则表示文本框里为二进制
Text1.Text = tostr(s) ' 执行二进制->文本转换
isstr = True
End If
End Sub

Private Sub Form_Load()
isstr = True ' 初始化设定文本框里为文本
End Sub

' 字符串到二进制换转函数,返回转换的二进制字符串表示
Function tobit(str As String) As String
Dim s$
Dim b&
For i = 1 To LenB(str) ' 8位一单元处理每个字节
b = CLng(AscB(MidB(str, i, 1)))
s = s & getbit(b) ' 转转每个字节
Next i
tobit = s
End Function

' 字节到二进制转换,返回转换的二进制字符串表示
Function getbit(num As Long) As String
Dim x&
Dim s$
x = &H80
For i = 1 To 8 ' 循环处理每一个bit
If num And x Then
s = s & 1 ' 此bit为1
Else
s = s & 0 ' 此bit为0
End If
x = x \ 2 ' x右移一位
Next i
getbit = s
End Function

' 还原二进制到字符串,返回原字符串
Function tostr(bitstr As String) As String
Dim e$, str$
Dim a&, b&, c&
While Len(bitstr) ' 一个字符16bit,宽字符
e = Mid(bitstr, 1, 8) ' 低八位
e = Mid(bitstr, 9, 8) + e ' 高八位
bitstr = Mid(bitstr, 17)
c = 1
b = 0
For i = 1 To 16 ' 循环处理每一位,实现转换
a = Asc(Right(e, i)) - 48
b = b + c * a
c = c * 2
Next i
str = str & ChrW(b)
Wend
tostr = str
End Function

回答2:

Private Declare Function icePub_BCDHexToHexString Lib "icePubDll.dll" (ByVal hexBuffer As String,ByVal strHexString As String,ByVal hexBufferLen As Integer) As Integer

Dim str1 As String
Dim a2 As Integer

str1=Space(1024*30)

a2=icePub_BCDHexToHexString("月光",str1,8)

MsgBox str1

Private Declare Function icePub_hexStringToBCDHex Lib "icePubDll.dll" (ByVal strHexString As String,ByVal hexBuffer As String,ByVal hexStringLen As Integer) As Integer

Dim buffer As String
Dim a2 As Integer

buffer=Space(1024*30)

a2=icePub_hexStringToBCDHex("D4C2B9E2",buffer,8)

MsgBox buffer
'压缩后可能是不可显数据

Private Declare Function icePub_hexStringToBinaryString Lib "icePubDll.dll" (ByVal strHex As String, ByVal strBinary As String) As Integer

Dim strResult As String
Dim a2 As Integer

strResult = Space(1024*8)
a2=icePub_hexStringToBinaryString("A1B2C3D4E5F87654321A",strResult)
MsgBox strResult

Private Declare Function icePub_binaryStringToHexString Lib "icePubDll.dll" (ByVal strBinary As String, ByVal strHex As String) As Integer

Dim strResult As String
Dim a2 As Integer

strResult = Space(1024)
a2=icePub_binaryStringToHexString("1001110001101",strResult)
MsgBox strResult

回答3:

文字怎么换二进制?是10进制数字换二进制数字?