美文网首页
ARC16校验

ARC16校验

作者: HuLL乐乐 | 来源:发表于2016-11-05 10:37 被阅读16次

    继承NSObject的类,加号方法
    {

    uint8_t byteArray[[data length]];
    [data getBytes:&byteArray length:[data length]];
    Byte CRC16Lo, CRC16Hi;   //CRC寄存器
    Byte CL, CH;             //多项式码&HA001
    Byte SaveLo, SaveHi;
    int i, Flag;
    
    CRC16Hi = 0xFF;
    CRC16Lo = 0xFF;
    
    CL = 0x1;
    CH = 0xA0;
    for (i = 0; i <[data length]; i++)
    {
        Byte bytes = byteArray[i];
        CRC16Lo = (Byte)(CRC16Lo ^ bytes); //每一个数据与CRC寄存器进行异或
        
        for (Flag = 0; Flag <= 7; Flag++)
        {
            SaveHi = CRC16Hi;
            SaveLo = CRC16Lo;
            CRC16Hi = (Byte)(CRC16Hi / 2);             //高位右移一位
            CRC16Lo = (Byte)(CRC16Lo / 2);             //低位右移一位
            
            if ((SaveHi & 0x1) == 0x1)
            {
                CRC16Lo = (Byte)(CRC16Lo | 0x80);
            }
            
            if ((SaveLo & 0x1) == 0x1)
            {
                CRC16Hi = (Byte)(CRC16Hi ^ CH);
                CRC16Lo = (Byte)(CRC16Lo ^ CL);
            }
        }
    }
    
    return (uint)CRC16Hi * 256 + CRC16Lo;
    

    }

    调用校验方法
    {

                NSString *strResult = @"08";//十六进制字符串08,放Byte数组是0x08
    
                Byte data[]={0xAA,0x55,0x04,0x00,0x21,0x11,strtoul([strResult UTF8String],0,16)};
    
                NSData *personData = [[NSData alloc] initWithBytes:data length:sizeof(data)/sizeof(data[0])];
    
                NSString *mstr = [NSString stringWithFormat:@"%04X",[CRC16CheckFunction crc16:personData]];
    
                [orderString appendString:mstr];
    

    }

    相关文章

      网友评论

          本文标题:ARC16校验

          本文链接:https://www.haomeiwen.com/subject/xzawuttx.html