Go與Android的CRC32/Adler32演算法使用

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。Packet在網路傳輸中必須要考慮萬一資料損毀的情況,CRC32與Adler32都是最常用的演算法。
Go與Android都內建好了這兩種演算法的實現,直接使用就好。

Go的調用方式如下:

// 校正演算法(ADLER32/CRC32)例子//author: Xiong Chuan Liang//date: 2015-4-12package mainimport ("fmt""hash/adler32""hash/crc32")var ADLER32 int = 0var CRC32 int = 1func main() {for _, v := range []string{"aaaaaaaaaa", "3333sdfsdffsdffsd", "234esrewr234324", `An Adler-32 checksum is obtained by calculating two 16-bit checksums A and B and concatenating their bits into a 32-bit integer. A is the sum of all bytes in the stream plus one, and B is the sum of the individual values of A from each step.At the beginning of an Adler-32 run, A is initialized to 1, B to 0. The sums are done modulo 65521 (the largest prime number smaller than 216). The bytes are stored in network order (big endian), B occupying the two most significant bytes.The function may be expressed asA = 1 + D1 + D2 + ... + Dn (mod 65521) B = (1 + D1) + (1 + D1 + D2) + ... + (1 + D1 + D2 + ... + Dn) (mod 65521)   = n×D1 + (n−1)×D2 + (n−2)×D3 + ... + Dn + n (mod 65521) Adler-32(D) = B × 65536 + Awhere D is the string of bytes for which the checksum is to be calculated, and n is the length of D.`} {calc(ADLER32, []byte(v))calc(CRC32, []byte(v))}}func calc(t int, b []byte) {var ret uint32if ADLER32 == t {ret = adler32.Checksum([]byte(b))fmt.Printf("ADLER32 %15d  : %s...  \n", ret, string(b[:5]))} else if CRC32 == t {ret = crc32.ChecksumIEEE([]byte(b))fmt.Printf("CRC32   %15d  : %s...  \n", ret, string(b[:5]))} else {return}}
      

     Android的就不舉例了,相關包有詳細說明:
CRC32:
http://wear.techbrood.com/reference/java/util/zip/CRC32.html
Adler32:
http://wear.techbrood.com/reference/java/util/zip/Adler32.html

兩者效果都差不多,不過Adler32相對來說計算量會小些。 


BLOG: http://blog.csdn.net/xcl168




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.