C# 和 OpenResty 中进行 CRC32

打印 上一主题 下一主题

主题 912|帖子 912|积分 2736

一、C# 进行 CRC32
  1. public class CRC32
  2. {
  3.     private static readonly uint[] _crc32Table;
  4.     static CRC32()
  5.     {
  6.         uint crc;
  7.         _crc32Table = new uint[256];
  8.         int i, j;
  9.         for (i = 0; i < 256; i++)
  10.         {
  11.             crc = (uint)i;
  12.             for (j = 8; j > 0; j--)
  13.             {
  14.                 if ((crc & 1) == 1)
  15.                     crc = (crc >> 1) ^ 0xEDB88320;
  16.                 else
  17.                     crc >>= 1;
  18.             }
  19.             _crc32Table[i] = crc;
  20.         }
  21.     }
  22.     /// <summary>
  23.     /// 获取CRC32校验值
  24.     /// </summary>
  25.     public static uint GetCRC32(byte[] bytes)
  26.     {
  27.         uint value = 0xffffffff;
  28.         int len = bytes.Length;
  29.         for (int i = 0; i < len; i++)
  30.         {
  31.             value = (value >> 8) ^ _crc32Table[(value & 0xFF) ^ bytes[i]];
  32.         }
  33.         return value ^ 0xffffffff;
  34.     }
  35.     /// <summary>
  36.     /// 获取CRC32校验值
  37.     /// </summary>
  38.     public static uint GetCRC32(string str)
  39.     {
  40.         byte[] bytes = Encoding.UTF8.GetBytes(str);
  41.         return GetCRC32(bytes);
  42.     }
  43. }
复制代码
使用方法
  1. string dataStr = "1234567890";
  2. var crcUint = CRC32.GetCRC32(dataStr);
  3. var crcHex = string.Format("{0:X8}", crcUint);
  4. Console.WriteLine($"{dataStr} => CRC32 Uint: {crcUint}, Hex: {crcHex}");
复制代码
结果:1234567890 => CRC32 Uint: 639479525, Hex: 261DAEE5
 
二、OpenResty 中进行 CRC32
  1. location /lua_crc {
  2.     content_by_lua_block
  3.     {
  4.         local str = "1234567890"
  5.         local crc32_long =  ngx.crc32_long(str)
  6.         ngx.say(str .. " => CRC32 long: " .. crc32_long, "</br>")
  7.     }
  8. }
复制代码
结果:1234567890 => CRC32 long: 639479525
C# 和 OpenResty 中进行 CRC32 的结果是一致的。
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

卖不甜枣

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表