Having mixed results when trying to translate a function using bitwise operations from Visual Basic to C#.
I'm sure I'm missing something really (visually) basic.
Here's the original VB code:
Dim CRCresult As UInt16 = 0
Dim CRC_16_POLY As UInt16 = &HA001
Private Sub CRC16(newByte As Byte)
CRCresult = CRCresult Xor newByte
For i As Integer = 0 To 7
If (CRCresult And &H1) Then
CRCresult = (CRCresult >> 1) Xor CRC_16_POLY
Else
CRCresult = (CRCresult >> 1)
End If
Next
End Sub
When I feed it the first 8 terms of this array:
{&H47, &H41, &H50, &H53, &H41, &HC, &H0, &H1, &H0, &H0, &H0, &HFF}
CRCresult appears as follows:
12864, 49395, 31104, 40248, 9949, 23782, 35549, 39307
Below is my translation to C#:
private UInt16 CRCresult = 0;
private UInt16 CRC_16_POLY = 0xA001;
private void CRC16(byte newByte)
{
CRCresult = (UInt16)(CRCresult ^ newByte);
for (int i = 0; i <= 7; i++) {
if((CRCresult & 0x1) != 0)
{
CRCresult = (UInt16)((CRCresult >> 1) ^ CRC_16_POLY);
} else
{
CRCresult = (UInt16)(CRCresult >> 1);
}
}
}
When I feed it the first 8 terms of this array:
{ 0x47, 0x41, 0x50, 0x53, 0x41, 0xC, 0x0, 0x1, 0x0, 0x0, 0x0, 0xFF }
CRCresult appears as follows:
12864, 49395, 31104, 40248, 57948, 15586, 18876, 29065
In summary
newBytes CRCresult
VB | C# | VB | C#
------------- ---------------
&H47 | 0x47 | 12864 | 12864
&H41 | 0x41 | 49395 | 49395
&H50 | 0x50 | 31104 | 31104
&H53 | 0x53 | 40248 | 40248
&H41 | 0x41 | 9949 | 57948
&HC | 0xC | 23782 | 15586
&H0 | 0x0 | 35549 | 18876
&H1 | 0x1 | 39307 | 29065
&H0 | 0x0 |
&H0 | 0x0 |
&H0 | 0x0 |
&HFF | 0xFF |
What am I missing in my translation that's causing the differences in the results?
both implementations are correct and produce same results
i found a sequence with a different value at pos 5 (index 4) &H4f
instead &H41
thisgenerate your (VB) results:
{&H47, &H41, &H50, &H53, &H4f, &HC, &H0, &H1, &H0, &H0, &H0, &HFF}
and this for (C#) results:
{&H47, &H41, &H50, &H53, &H41, &HC, &H0, &H1, &H0, &H0, &H0, &HFF}
maybe a small typing error in your test data? :-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.