Vb.net 计算UTF8 readpos
实际上,我在代码中使用了这个:Vb.net 计算UTF8 readpos,vb.net,utf-8,Vb.net,Utf 8,实际上,我在代码中使用了这个: 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 Stri
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转换成UTF8,谁有提示或解决方案?
你应该强烈地考虑BialReald/Wrror。< /P> 但是,如果您遇到这个问题,请通过写入字节数而不是字符串长度来解决问题:
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很难看,它会产生太多的垃圾。不知道Buff可能是什么,如果它是一个MemoryStream,那么就使用GetBuffer()