우선 게시 된 코드는 문자열 중 가장 짧은 문자열에 대한 예외를 throw합니다.
다음 코드에는 OP의 원래 코드와 간단한 체크섬 및 체크섬 사용 방법이 나와 있습니다.
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Dim buffer() As Byte
Dim tstString As String = "Calculate a checksum for a given string"
Dim chkSumFix As Integer = CreateIntChecksumFixed(tstString) 'get a checksum
buffer = SendPacket(tstString, chkSumFix) 'create a byte buffer to send
tstString = decodePacket(buffer)
'do the same using the OP's original code
Dim chkSum As Integer = CreateIntChecksum(tstString) 'error
buffer = SendPacket(tstString, chkSum)
End Sub
'OP
Public Function CreateIntChecksum(ByVal s As String) As Integer
Dim r As Integer = 0
For i As Integer = 0 To (s.Length() - 1)
Dim bchar As Byte = Convert.ToByte(s(i))
r = bchar + ((r << 5) - r)
Next
Return r
End Function
'a very simple checksum
Public Function CreateIntChecksumFixed(ByVal s As String) As Integer
Dim r As Integer = 0
For i As Integer = 0 To (s.Length() - 1)
Dim bchar As Byte = Convert.ToByte(s(i))
r = (r And &HFFFF) + bchar
Next
Return r
End Function
Private Function SendPacket(ByVal aString As String, _
ByVal aChecksum As Integer) As Byte()
'construct a packet to be sent
'Packet format
'returns a byte buffer
'byte(0 -3) = length of original string - use BitConverter.ToInt32 to extract
'byte(4-n) = original string. n = (4 + string length) - 1
'byte(n + 1, n + 2, n + 3, n + 4) = checksum
Dim length As Integer
Dim retV As New List(Of Byte)
retV.AddRange(System.Text.Encoding.ASCII.GetBytes(aString)) 'add string to packet
length = retV.Count 'get length - use this length in case a different encoding is used
retV.AddRange(BitConverter.GetBytes(aChecksum)) 'add checksum
retV.InsertRange(0, BitConverter.GetBytes(length)) 'insert length at start of packet
Return retV.ToArray
End Function
Private Function decodePacket(ByVal buffer As Byte()) As String
Dim sLen As Integer = BitConverter.ToInt32(buffer, 0)
If sLen + 8 <> buffer.Length Then Throw New ArgumentOutOfRangeException
Dim s As String = System.Text.Encoding.ASCII.GetChars(buffer, 4, sLen)
Dim chksum As Integer = CreateIntChecksumFixed(s)
Dim embeddedChecksum As Integer = BitConverter.ToInt32(buffer, sLen + 4)
If chksum <> embeddedChecksum Then Throw New ArgumentException("Invalid checksum")
Return s
End Function
두 단어 : 나는 가능합니다. 해시 또는 체크섬 기능이 무엇인지 그리고 그 용도를 찾아야합니다. 어쨌든'Integer' 값보다'String' 값이 더 많으므로 역 매핑이 불가능합니다. –
@Charles Bailey 두 단어? – Stephen
고의적 인 금권 주의자 : http://en.wikipedia.org/wiki/Samuel_Goldwyn –