16進(jìn)制字符串轉(zhuǎn)化為字節(jié)(byte)數(shù)組记劈,16進(jìn)制字符串的異或運(yùn)算:
-(NSString*)generateCRC:(NSString*)str{
? ? //把16進(jìn)制字符串轉(zhuǎn)換成字節(jié)數(shù)組
? ? long len = ([str length]/2);
? ? int j=0;
? ? Byte result[str.length/2];
? ? for(inti=0;i<[str length];i++)
? ? {
? ? ? ? int int_ch;? // 兩位16進(jìn)制數(shù)轉(zhuǎn)化后的10進(jìn)制數(shù)
? ? ? ? unichar hex_char1 = [strcharacterAtIndex:i];//兩位16進(jìn)制數(shù)中的第一位(高位*16)
? ? ? ? int int_ch1;
? ? ? ? if(hex_char1 >='0'&& hex_char1 <='9')
? ? ? ? {
? ? ? ? ? ? int_ch1 = (hex_char1-48)*16;? ? ? // 0 的Ascll - 48
? ? ? ? }
? ? ? ? else if(hex_char1 >='A'&& hex_char1 <='F')
? ? ? ? {
? ? ? ? ? ? int_ch1 = (hex_char1-55)*16;? // A 的Ascll - 65
? ? ? ? }
? ? ? ? else
? ? ? ? {
? ? ? ? ? ? int_ch1 = (hex_char1-87)*16;? // a 的Ascll - 97
? ? ? ? }
? ? ? ? i++;
? ? ? ? unichar hex_char2 = [strcharacterAtIndex:i];//兩位16進(jìn)制數(shù)中的第二位(低位)
? ? ? ? int int_ch2;
? ? ? ? if(hex_char2 >='0'&& hex_char2 <='9')
? ? ? ? {
? ? ? ? ? ? int_ch2 = (hex_char2-48);? // 0 的Ascll - 48
? ? ? ? }
? ? ? ? else if(hex_char2 >='A'&& hex_char2 <='F')
? ? ? ? {
? ? ? ? ? ? int_ch2 = hex_char2-55;? // A 的Ascll - 65
? ? ? ? }
? ? ? ? else
? ? ? ? {
? ? ? ? ? ? int_ch2 = hex_char2-87;? // a 的Ascll - 97
? ? ? ? }
? ? ? ? int_ch = int_ch1+int_ch2;
? ? ? //? NSLog(@"int_ch=%d",int_ch);
? ? ? ? result[j] = int_ch;? //將轉(zhuǎn)化后的數(shù)放入Byte數(shù)組里
? ? ? ? j++;
? ? }
// 異或運(yùn)算
? ? Byte check[1];
? ? NSString*hexStr=@"";
? ? for(inti =0; i
? ? ? ? if(i ==0) {
? ? ? ? ? ? check[0] = result[0];
? ? ? ? }else{
? ? ? ? ? ? check[0] ^=result[i];
? ? ? ? }
? ? }
? ? NSData*adata = [[NSData alloc]initWithBytes:checklength:1];
? ? hexStr = [self HexStringWithData:adata];
? ? hexStr = [hexStr uppercaseString];
? ? return hexStr;
}
-(NSString*)HexStringWithData:(NSData*)data{
? ? Byte*bytes = (Byte*)[databytes];
? ? NSString*hexStr=@"";
? ? for(inti=0;i<[datalength];i++) {
? ? ? ? NSString*newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16進(jìn)制數(shù)
? ? ? ? if([newHexStrlength]==1){
? ? ? ? ? ? hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
? ? ? ? }
? ? ? ? else{
? ? ? ? ? ? hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
? ? ? ? }
? ? }
? ? hexStr = [hexStr uppercaseString];
? ? return hexStr;
}