Go与Android的CRC32/Adler32算法使用

       Packet在网络传输中必须要考虑万一数据损坏的情况,CRC32与Adler32都是最常用的算法。
Go与Android都内置好了这两种算法的实现,直接使用就好。

Go的调用方式如下:

// 校验算法(ADLER32/CRC32)例子
//author: Xiong Chuan Liang
//date: 2015-4-12

package main

import (
	"fmt"
	"hash/adler32"
	"hash/crc32"
)

var ADLER32 int = 0
var CRC32 int = 1

func 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 as
					A = 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 + A
					where 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 uint32
	if 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




郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。