十六进制字符串转NSData
-(NSData *)converHexStrToData:(NSString *)hexString {
NSMutableData *data = [[NSMutableData alloc] init];
unsigned char whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
if (hexString.length%2) {
//防止丢失半个byte
hexString = [@"0" stringByAppendingString:hexString];
}
int i;
for (i = 0; i < [hexString length]/2; i++) {
byte_chars[0] = [hexString characterAtIndex:i * 2];
byte_chars[1] = [hexString characterAtIndex:i * 2 + 1];
whole_byte = strtol(byte_chars, NULL, 16);
[data appendBytes:&whole_byte length:1];
}
return data;
}
NSData转十六进制字符串
-(NSString *) converDataToHexString:(NSData *)data
{
if (data == nil) {
return nil;
}
NSMutableString* hexString = [NSMutableString string];
const unsigned char *p = [data bytes];
for (int i=0; i < [data length]; i++) {
[hexString appendFormat:@"%02x", *p++];
}
return hexString;
}
十六进制字符串转普通字符串
-(NSString *)stringFromHexString:(NSString *)hexString {
char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
bzero(myBuffer, [hexString length] / 2 + 1);
for (int i = 0; i < [hexString length] - 1; i += 2) {
unsigned int anInt;
NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
[scanner scanHexInt:&anInt];
myBuffer[i / 2] = (char)anInt;
}
NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
return unicodeString;
}
网友评论