CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2005
    Posts
    60

    [RESOLVED] crc 16 ccitt 8408

    i need a function to calculate the CRC16 from a string, not a byte array

    this is the function from the documentation of the device, but its in C

    Code:
    word reentrant update_crc16 (word oldcrc, byte d)
    {
        word crc, carry, b;
        byte i;
    
        crc = oldcrc;
        for (i = 0; i < 8; ++i)
        {
            b = (d & (0x01 << i))?0x0001:0x0000;
            carry = (crc & 0x0001) ^ b;
            crc >>= 1;
            if(carry)crc ^= 0x8408;
        }
    
        return crc;
    }
    
    // you must initialize the initial crc with 0x8408
    i already have a equivalent function to do bit-shift in VB (<< >>=)

    but i dont understand that line :
    b = (d & (0x01 << i))?0x0001:0x0000;
    and the word "reentrant"

  2. #2
    Join Date
    Jul 2006
    Location
    Germany
    Posts
    3,725

    Re: crc 16 ccitt 8408

    What you see there is a conditional expression, best replaced by vb's IIf()
    It is an expression with an implicit If/Then/Else.
    Let's translate:
    b = (d & (0x01 << i))?0x0001:0x0000;

    Code:
    'As If Then Else:
    If d And (1 * 2^i) Then b = 1 Else b = 0
    'As IIf:
    b = IIf(d And (1 * 2^i), 1, 0)
    The (0x01 << i) cn be simplified to 2^i in the end. Same as 1 * 2^i

    Reentrant means, that the function must be written so that it can call itself.

  3. #3
    Join Date
    Jun 2005
    Posts
    60

    Re: crc 16 ccitt 8408

    thanks, its working

    Code:
    Private Function CRC16(ByVal crc As Integer, d As Byte) As Integer
      Dim carry As Integer, i As Byte
      For i = 0 To 7
        carry = (crc And 1) Xor IIf(d And (2 ^ i), 1, 0)
        crc = (crc And &HFFFF&) \ 2
        If carry <> 0 Then crc = crc Xor &H8408
      Next i
      CRC16 = crc
    End Function
    
    Public Function CalcCrc16(ByVal buf As String) As String
      Dim crc As Integer, t As Integer
      crc = &H8408
      For t = 1 To Len(buf)
        crc = CRC16(crc, Asc(Mid$(buf, t, 1)))
      Next t
      CalcCrc16 = Chr$(HiByte(crc)) & Chr$(LoByte(crc))
    End Function
    Last edited by sergelac; April 17th, 2009 at 10:57 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured