python CRC16檢驗__python

來源:互聯網
上載者:User
CRC16計算.py
#! /usr/bin/python # _*_ coding: utf-8 _*_  """ 簡單的CRC16計算樣本:     CRC16校正碼計算方法如下:     1、初始化CRC值為0xFFFF     2、被檢驗數的第1位元組跟CRC的低8位異或,將結果放入CRC的低8位(CRC的高8位不變)     3、CRC右移1位,若移出的為0繼續右移;為1CRC寄存器跟產生多項式(倒序後的值)異或(X16+X15+X2+1 <--> 0x8005 >>> 0xA0001)     4、重複步驟3,8次第1字字資料處理完成     5、取被檢驗資料的下1位元組,進行2、3、4步;至到整個資料檢驗完成     6、將最後的CRC值,高低位元組交換 """  # CRC16產生多項式:X16+X15+X2+1 GENERATOR_POLYNOMIAL = 0x8005 # CRC初始值為:0xFFFF CRC = 0xFFFF  def calculateCRC(dataarray):     """     檢查輸入資料是否合法     :param dataarray: 需要產生CRC校正的資料     :return: 合法的資料元組     """     datalist = dataarray.split()    #以空格分割字串得到對應字串列表     print(u'輸入的字串序列:{0}'.format(datalist))      index = 0     try:         # 將輸入的字串按不同進位數轉化為資料序列         for index, item in enumerate(datalist):             # print index,item             if '0x'in item.lower().strip():                 datalist[index] = int(item, 16)             elif '0o' in item.lower().strip():                 datalist[index] = int(item,8)             elif '0b' in item.lower().strip():                 datalist[index] = int(item,2)             else:                 datalist[index] = int(item)         print (u'成功轉換後的對應的序列:{0}'.format(datalist))         # 處理第1個位元組資料         temp = calculateonebyte(datalist.pop(0), 0xFFFF)         # 迴圈處理其它位元組資料         for data in datalist:             temp = calculateonebyte(data,temp)         return temp      except ValueError as err:         print(u'第{0}個資料{1}輸入有誤'.format(index,datalist[index]).encode('utf-8'))         print(err)     # finally:     #     print('當前datalist:{0} '.format(datalist))  def calculateonebyte(databyte, tempcrc):     """     計算1位元組資料的CRC值     :param databyte: 需計算的位元組資料     :param tempcrc: 當前的CRC值     :return: 當道新的CRC值     """     # databyte必須為位元組資料     # assert 0x00 <= databyte <= 0xFF     # 同上位元組資料檢查     if not 0x00 <= databyte <= 0xFF:         raise Exception((u'資料:0x{0:<02X}不是位元組資料[0x00-0xFF]'.format(databyte)).encode('utf-8'))      # 把位元組資料根CRC當前值的低8位相異或     low_byte = (databyte ^ tempcrc) & 0x00FF     # 當前CRC的高8位值不變     resultCRC = (tempcrc & 0xFF00) | low_byte      # 迴圈計算8位元據     for index in range(8):         # 若最低為1:CRC當前值跟產生多項式異或;為0繼續         if resultCRC & 0x0001 == 1:             #print("[%d]: 0x%4X ^^^^ 0x%4X" % (index,resultCRC>>1,resultCRC^GENERATOR_POLYNOMIAL))             resultCRC >>= 1             resultCRC ^= 0xA001 # 0xA001是0x8005迴圈右移16位的值         else:             # print ("[{0}]: 0x{1:X} >>>> 0x{2:X}".format(index,resultCRC,resultCRC>>1))             resultCRC >>= 1      return resultCRC   if __name__ == '__main__':     data_string = '0x01 2 0o3'  #以16進位,10進位,8進位輸入的資料流     print('資料 :"{0:s}"對應的CRC16檢驗碼為:0x{1:04X}'.format(data_string,calculateCRC(data_string)))      

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.