2014-07-11 76 views
1

嗯,其實我在我的代碼中使用此:計算UTF8 readpos

Public Sub WriteString(ByVal Input As String) 
    Buff.AddRange(BitConverter.GetBytes(Input.Length)) 
    Buff.AddRange(Encoding.Unicode.GetBytes(Input)) 
End Sub 
Public Function ReadString(Optional ByVal Peek As Boolean = True) As String 
    Dim Len As Integer = ReadInteger(True) * 2 
    Dim ret As String = Encoding.Unicode.GetString(Buff.ToArray, readpos, Len) 
    If Peek And Buff.Count > readpos Then 
     If ret.Length > 0 Then 
      readpos += Len 
     End If 
    End If 
    Return ret 
End Function 

功能ReadInteger:

Public Function ReadInteger(Optional ByVal peek As Boolean = True) As Integer 
    If Buff.Count > readpos Then 'check to see if this passes the byte count 
     Dim ret As Integer = BitConverter.ToInt32(Buff.ToArray, readpos) 
     If peek And Buff.Count > readpos Then 
      readpos += 4 
     End If 
     Return ret 
    Else 
     Throw New Exception("Byte Buffer Past Limit!") 'past byte count throw a new exception 
    End If 
End Function 

我想的Unicode更改爲UTF-8,任何人有提示或解決方案?

回答

1

你應該強烈考慮BinaryReader/Writer。

但如果你堅持這種然後通過寫入的字節,不是字符串的長度數解決您的問題:

Public Sub WriteString(ByVal Input As String) 
    Dim bytes = Encoding.UTF8.GetBytes(Input) 
    Buff.AddRange(BitConverter.GetBytes(bytes.Length)) 
    Buff.AddRange(bytes) 
End Sub 

Public Function ReadString(Optional ByVal Peek As Boolean = True) As String 
    Dim bytes = ReadInteger(True) 
    Dim str = Encoding.UTF8.GetString(Buff.ToArray, readpos, bytes) 
    readpos += bytes 
    Return str 
End Function 

請注意,Buff.ToArray是醜陋的,它創建垃圾太多了。如果它是一個MemoryStream,那麼不用Buff的想法,那麼可以使用GetBuffer()。