1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- /// <summary>
- /// CRC32相关工具集
- /// </summary>
- public partial class Utils
- {
- /// <summary>
- /// key
- /// </summary>
- private static ulong[] Crc32Table;
- /// <summary>
- /// 获取指定字符串的CRC32值
- /// </summary>
- /// <param name="str">源串</param>
- /// <returns>经crc32换算后的数值</returns>
- public static ulong CRC32(string str)
- {
- GetCRC32Tale();
- byte[] buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(str);
- 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;
- }
- /// <summary>
- /// 创建CRC32因子
- /// </summary>
- private static void GetCRC32Tale()
- {
- 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;
- }
- }
- }
|