标签:
一、各个之间的相互转换
1、字符串转数据流NSData
NSString *str = @"abc123"; NSData *dd = [str dataUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%@",dd); // dd = <61626331 3233>
通过打印转换后的数据流可以看到,数据流里是两位一个字节存储字符串ASCII码的十六进制,a = 97 = 0x61, 1 = 49 = 0x31
2、字节与数据流转换
Byte bb[] = {97,98,99,49,50,51};
NSData *dd = [[NSData alloc]initWithBytes:bb length:6];
NSLog(@"%@",dd); // dd = <61626331 3233> 打印的结果和字符串转换是一样的
//数据流转字节
Byte *bb = (Byte *)[dd bytes];
3、根据需要直接变成NSData,倒过来同理NSData转字符串也是先变成字节在转字符串
NSString *bcdstr = @"616263313233";
int leng = (int)bcdstr.length/2;
if (bcdstr.length%2 == 1) //判断奇偶数
{
leng +=1;
}
Byte bbte[leng];
for (int i = 0; i<leng-1; i++)
{
bbte[i] = (int)strtoul([[bcdstr substringWithRange:NSMakeRange(i*2, 2)]UTF8String], 0, 16);
}
if (bcdstr.length%2 == 1)
{
bbte[leng-1] = (int)strtoul([[bcdstr substringWithRange:NSMakeRange((leng - 1)*2, 1)]UTF8String], 0, 16) *16;
}else
{
bbte[leng-1] = (int)strtoul([[bcdstr substringWithRange:NSMakeRange((leng - 1)*2, 2)]UTF8String], 0, 16);
}
NSData *de = [[NSData alloc]initWithBytes:bbte length:leng];
NSLog(@"%@",de); //<61626331 3233>
二、MD5计算
1、字符串的MD5计算
+(NSString *)md5HexDigest:(NSString *)str
{
const char *original_str = [str UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH]; //16
CC_MD5(original_str, (int)strlen(original_str), result);
NSMutableString *hash = [NSMutableString string];
for (int i = 0; i < 16; i++)
{
[hash appendFormat:@"%02x", result[i]];//两位表示 不足两位补0
}
return [hash lowercaseString];
}
2、字符串的MD5计算
+(NSString*)getMD5WithData:(NSData *)data
{
//不要把数据流先转成char,不然如果遇到00字节就不会计算00后面数据
unsigned char result[16];
CC_MD5([data bytes], (int)[data length], result);
NSMutableString *hash = [NSMutableString string];
for (int i = 0; i < 16; i++)
{
[hash appendFormat:@"%02x", result[i]];//x就是小写的字母,X就是大写的字母,2个字节不足补0
}
return hash;
}
标签:
原文地址:http://www.cnblogs.com/qq95230/p/MD5.html