最近在看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] =