2017-06-27 35 views
0

我想將我的bytearray轉換爲二進制文件,例如:「01010101」。對於小文件,它可以無任何問題地進行轉換,但轉換大文件花費的時間太長(即使只有5MB,我也無法想象任何大於此的文件)。有沒有更快的方法將此bytearray轉換爲二進制,反之亦然? 這裏是我的代碼快速的方法來轉換字節數組爲二進制的VB?

Public Function conv_FileToByte(ByVal filename As String) 

    Dim convFileToByte_array() As Byte 
    Dim fs As New FileStream(filename, FileMode.Open, FileAccess.Read) 
    Dim fileData As Byte() = New Byte(fs.Length - 1) {} 

    Console.WriteLine("reading file data") 
    fs.Read(fileData, 0, Convert.ToInt32(fs.Length)) 
    fs.Close() 
    Console.WriteLine("close stream") 


    convFileToByte_array = fileData 

    Console.WriteLine("Returning value") 

    Return convFileToByte_array 

End Function 


Public Function conv_ByteToBin(ByVal conv() As Byte) 

    'Dim newBin As New List(Of String) 
    Dim newBin As String = Nothing 
    For Each c In conv 
     'newBin.Add(Convert.ToString(c, 2).PadLeft(8, "0")) 
     Dim temp_bin As String 
     temp_bin = Convert.ToString(c, 2).PadLeft(8, "0") 
     newBin = newBin & temp_bin 
    Next 
    Console.WriteLine("Returning value") 

    Return newBin 
End Function 


Public Function conv_BinToByte(ByVal binValue As String) 


    Dim count_binValue As String = binValue.Count 

    Dim temp_binValue As New List(Of String) 


    Dim bins As New Byte() 
    Dim binlist As New List(Of Byte) 

    For i As Integer = 0 To count_binValue - 1 Step 8 


     Dim temp_value As String 
     temp_value = binValue.Substring(i, 8) 


     Dim convert_temp As String 

     convert_temp = Convert.ToInt32(temp_value, 2) 

     temp_binValue.Add(convert_temp) 
    Next 

    For Each bl In temp_binValue 
     binlist.Add(bl) 
    Next 


    Dim binData As Byte() = New Byte(binlist.Count - 1) {} 
    For bd As Integer = 0 To binlist.Count - 1 
     binData(bd) = binlist(bd) 
    Next 

    Return binData 

End Function 

回答

2

您在conv_ByteToBin法串聯非常大的字符串。在這種情況下,使用基本字符串連接是非常糟糕的做法,看起來這是您的瓶頸。我只是改變了方法,使用StringBuilder,因爲它是來連接大串和代碼運行得一種有效的方式,更快:

Public Function conv_ByteToBin(ByVal conv() As Byte) As String 
    Dim newBin As New StringBuilder 

    For Each c In conv 
     newBin.Append(Convert.ToString(c, 2).PadLeft(8, "0")) 
    Next 
    Console.WriteLine("Returning value") 

    Return newBin.ToString 
End Function 

最佳實踐提示:

  • 在你的方法總是使用返回類型
  • FileStream實現IDisposable - 使用塊始終使用與實現IDisposable

而且你的方法conv_Fil對象eToByte是無關緊要的,因爲.net已經建立在File.ReadAllBytes - 方法完成相同的事情。只需調用它並刪除自己的實現。

+0

謝謝,這解決了我的問題!我不知道這很簡單。 – totallynewbie

相關問題