ToB企服应用市场:ToB评测及商务社交产业平台

标题: C# 和 OpenResty 中进行 CRC32 [打印本页]

作者: 卖不甜枣    时间: 2023-7-18 23:52
标题: C# 和 OpenResty 中进行 CRC32
一、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 的结果是一致的。
 

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




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4