问题:读一个文本文件,以二进制输出(实际上是十六进制)。
如,一个以ascii编码的文件内容为 "abc 测", 我要输出显示为"61 62 63 B2 E2".
本来我想这样做的:
Private Sub Text1_Change()
    
    Text2.Text = ""
    
    For i = 1 To Len(Text1.Text)
        bChar = MidB(Text1.Text, i, 1)
        c = Int(Asc(bChar) / 16) & (Asc(bChar) Mod 16)
        Text2.Text = Text2.Text + " " + c
    Next i
    Text2.Refresh
End Sub
但是MidB这句话有错,如果用Mid,对于中文又无法辨认。请VB版的高手指点一下,谢谢!

解决方案 »

  1.   

    Private Sub Text1_Change()
    Dim bytData() As Byte
    Dim i As Long
        Text2.Text = ""
        If Text1.Text = "" Then
            Exit Sub
        End If
        bytData = StrConv(Text1.Text, vbFromUnicode)
        Text2.SelText = Hex(bytData(0))
        For i = 1 To UBound(bytData)
            Text2.SelText = " "
            Text2.SelText = Hex(bytData(i))
        Next i
    End Sub
      

  2.   

    用二进制读取出对应字节的数值,然后转换成16进制
    Private Declare Function lopen Lib "kernel32" Alias "_lopen" (ByVal lpPathName As String, ByVal iReadWrite As Long) As Long
    Private Declare Function lread Lib "kernel32" Alias "_lread" (ByVal hFile As Long, lpBuffer As Any, ByVal wBytes As Long) As Long
    Private Declare Function lclose Lib "kernel32" Alias "_lclose" (ByVal hFile As Long) As LongConst READAPI = 0        '  Flags for _lopen
    Const WRITEAPI = 1
    Const READ_WRITE = 2Private Sub Form_Load()
        Dim hFile As Long
        Dim FLen As Long
        Dim str As String
        Dim lBuffer As Long
        Dim i As Long
        i = 1
       
        FLen = FileLen("C:\2.txt")
        hFile = lopen("C:\2.txt", READAPI)
        If IsNumeric(hFile) Then '如果打开成功
            While i <= FLen
                lread hFile, lBuffer, 1
                str = str & " " & Hex(lBuffer)
                i = i + 1
            Wend
            MsgBox str
        End If
    End Sub
      

  3.   

    Private Sub Text1_Change()
        
        Text2.Text = ""
        
        For i = 1 To Len(Text1.Text)
            intChar = MidB(Text1.Text, i, 1)
            strTmp = Hex(intChar)
            If intChar < 0 Then '双字节文字
                Text2.Text = Text2.Text + " " + Left(strTmp, 2) + " " + mid(strTmp, 3,2)
            Else 
                Text2.Text = Text2.Text + " " + strTmp
            End If
        Next i
        Text2.Refresh
    End Sub
      

  4.   

    更正,不要用 MidB:
    Private Sub Text1_Change()
        
        Text2.Text = ""
        
        For i = 1 To Len(Text1.Text)
            intChar = Chr(Mid(Text1.Text, i, 1))
            strTmp = Hex(intChar)
            If intChar < 0 Then '双字节文字
                Text2.Text = Text2.Text + " " + Left(strTmp, 2) + " " + Mid(strTmp, 3,2)
            Else 
                Text2.Text = Text2.Text + " " + strTmp
            End If
        Next i
        Text2.Refresh
    End Sub
      

  5.   

    还是忙中出错:
    intChar = Asc(Mid(Text1.Text, i, 1))