C# CRC16 和汉明重量

本文介绍了在Redis集群中用于分配Key的CRC16算法,并提供了C#实现。同时,文章讨论了Redis的bitcount函数内的汉明重量算法,特别是针对长度为32的字节数组的实现。文中还提到了优化算法时要考虑的时间复杂度和空间复杂度。
摘要由CSDN通过智能技术生成

最近在看redis之类的pdf,发现redis在做集群的时候,不同的key分到不同的主服务器,其中划分key的算法采用CRC16算法,所以特此整理一下其C#code如下:

  #region CRC16
        /// <summary>
        /// Computes the hash-slot that would be used by the given key
        /// </summary>
        public static unsafe int HashSlot(string key)
        {
            //HASH_SLOT = CRC16(key) mod 16384
            if (string.IsNullOrEmpty(key)) return -1;
            unchecked
            {
                //var blob = (byte[])key;
                var blob = Encoding.UTF8.GetBytes(key);
                fixed (byte* ptr = blob)
                {
                    int offset = 0, count = blob.Length, start, end;
                    if ((start = IndexOf(ptr, (byte)'{
   ', 0, count - 1)) >= 0
                        && (end = IndexOf(ptr, (byte)'}', start + 1, count)) >= 0
                        && --end != start)
                    {
                        offset = start + 1;
                        count = end - start; // note we already subtracted one via --end
                    }

                    uint crc = 0;
                    for (int i = 0; i < count; i++)
                        crc = ((crc << 8) ^ crc16tab[((crc >> 8) ^ ptr[offset++]) & 0x00FF]) & 0x0000FFFF;
                    return (int)(crc % 16384);
                }
            }
        }
        static unsafe int IndexOf(byte* ptr, byte value, int start, int end)
        {
            for (int offset = start; offset < end; offset++)
                if (ptr[offset] =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值