C# 和 Java 中CRC32 对应校验

项目中用到CRC32进行校验得地方,需要用到C#和java进行对比,直接贴代码网上拷贝得很容易

class CRC32Cls
    {
        protected ulong[] Crc32Table;
        //生成CRC32码表
        public void GetCRC32Table()
        {
            ulong Crc;
            Crc32Table = new ulong[256];
            int i, j;
            for (i = 0; i < 256; i++)
            {
                Crc = (ulong)i;
                for (j = 8; j > 0; j--)
                {
                    if ((Crc & 1) == 1)
                        Crc = (Crc >> 1) ^ 0xEDB88320;
                    else
                        Crc >>= 1;
                }
                Crc32Table[i] = Crc;
            }
        }

        //获取字符串的CRC32校验值
        public ulong GetCRC32Str(string sInputString)
        {
            //生成码表
            GetCRC32Table();
            //byte[] buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(sInputString);//根据自己不同得需求,跟java同步用即可保证统一
            byte[] buffer = System.Text.Encoding.Default.GetBytes(sInputString);
            //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sInputString);
            ulong value = 0xffffffff;
            int len = buffer.Length;
            for (int i = 0; i < len; i++)
            {
                value = (value >> 8) ^ Crc32Table[(value & 0xFF) ^ buffer[i]];
            }
            return value ^ 0xffffffff;
        }
    }

调用代码

string value = String.Format("{0:X00000000}", CRC32Cls.GetCRC32Str(cont));//内容不会加0

string value = String.Format("{0:X8}", CRC32Cls.GetCRC32Str(cont)); //内容中最前面会加入0
java代码同理
package CRCTest;
import java.io.UnsupportedEncodingException;
import java.util.zip.CRC32;
import java.util.zip.Checksum;

public class test {

    public static void main(String[] args) throws UnsupportedEncodingException {
        
        long con= crc32("测试123ABC!@#$%^&*()");
        System.out.print(Long.toHexString(con).toUpperCase());// TODO Auto-generated method stub

    }
    public static long crc32(String data) throws UnsupportedEncodingException {
        if (data == null) {
            return -1;
        }

        // get bytes from string
        byte bytes[] = data.getBytes("UTF-8");//这里编码需要跟C# 保持同步
        //byte bytes[] = data.getBytes();
        Checksum checksum = new CRC32();
        // update the current checksum with the specified array of bytes
        checksum.update(bytes, 0, bytes.length);
        // get the current checksum value
        return checksum.getValue();
    }
}
这样得出来得结果即可相同。

 

posted @ 2022-02-16 17:05  w_junguang  阅读(391)  评论(0编辑  收藏  举报