ios crc16校验,经验证可用 含 多项式、初始值

+ (NSData *)getCrcVerifyCode:(NSData *)data {
    int crcWord = 0x0000ffff;  // 初始值
    
    Byte *dataArray = (Byte *)[data bytes];
    for (NSInteger i = 0; i < data.length; i++) {
        Byte byte = dataArray[i];
        crcWord ^= (int)byte & 0x000000ff;
        for (NSInteger j = 0; j < 8; j++) {
            if ((crcWord & 0x00000001) == 1) {
                crcWord = crcWord >> 1;
                crcWord = crcWord ^ 0x0000a001; // 0x0000a001 多项式
            }else {
                crcWord = (crcWord >> 1);
            }
        }
    }

    Byte crcH = (Byte)0xff & (crcWord >> 8);
    Byte crcL = (Byte)0xff & crcWord;
    Byte arraycrc[] = {crcH,crcL};
    NSData *datacrc = [[NSData alloc] initWithBytes:arraycrc length:sizeof(arraycrc)];

    return datacrc;
}

你可能感兴趣的:(ios crc16校验,经验证可用 含 多项式、初始值)