2015-08-28 15:41:01 kongu 阅读数 3013

iOS 二进制数组转成16进制字符串

 Byte bytes[28];
 [data getBytes:bytes length:28];

 NSMutableString *hexString = [[NSMutableString alloc] init];
 for (int i = 0; i < 28; i++) {
      NSLog(@"%hhu",bytes[i]);
      [hexString appendString:[NSString stringWithFormat:@"%0.2hhx", bytes[i]]];
 }

 NSLog(@" %@  ", hexString);

字符串转二进制

int len = [self length] / 2;    // Target length  
unsigned char *buf = malloc(len)  
unsigned char *whole_byte = buf;  
char byte_chars[3] = {'\0','\0','\0'};  

int i;  
for (i=0; i < [self length] / 2; i++) {  
    byte_chars[0] = [self characterAtIndex:i*2];  
    byte_chars[1] = [self characterAtIndex:i*2+1];  
    *whole_byte = strtol(byte_chars, NULL, 16);  
    whole_byte++;  
}  

NSData *data = [NSData dataWithBytes:buf length:len];  
free( buf );  
return data; 
2015-10-25 20:28:59 wang1018960145 阅读数 2317

下面这个是将16进制转换成2进制数据

+ (NSData *)hex2data:(NSString *)hex {
    NSMutableData *data = [NSMutableData dataWithCapacity:hex.length / 2];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < hex.length / 2; i++) {
        byte_chars[0] = [hex characterAtIndex:i*2];
        byte_chars[1] = [hex characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [data appendBytes:&whole_byte length:1];
    }
    return data;
    
}


2019-09-24 14:25:17 WangQingLei0307 阅读数 19

 

最近解除了一个项目需要进行各种进制之间和类型的之间的转化,今天和大家分享一下,希望对大家有帮助

第一个就是NSData进行异或计算(^就代表异或操作),再高级语言中这种计算方式可以说是很陌生的,平常基本使用不到今天分享一下计算过成

    __block uint8_t result = '\0' ;
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            uint8_t cha = dataBytes[i];
            //此处代码为异或操作复制到result中
            result^=cha;
        }
    }];

将data放入该方法中,开始循环这个data.bytes内容,result就是最终结果。

将10进制转16进制


/**
 十进制转换十六进制
 
 @param decimal 十进制数
 @return 十六进制数
 */
+ (NSString *)getHexByDecimal:(NSInteger)decimal {
    
    NSString *hex =@"";
    NSString *letter;
    NSInteger number;
    for (int i = 0; i<9; i++) {
        
        number = decimal % 16;
        decimal = decimal / 16;
        switch (number) {
                
            case 10:
                letter =@"A"; break;
            case 11:
                letter =@"B"; break;
            case 12:
                letter =@"C"; break;
            case 13:
                letter =@"D"; break;
            case 14:
                letter =@"E"; break;
            case 15:
                letter =@"F"; break;
            default:
                letter = [NSString stringWithFormat:@"%ld", number];
        }
        hex = [letter stringByAppendingString:hex];
        if (decimal == 0) {
            
            break;
        }
    }
    return hex;
}

16进制形式的字符串转成16进制NSData类型


/**
 将16进制类型的字符串转成16进制的NSData类型

 @param str 字符串
 @return nsdata
 */
+ (NSData *)convertHexStrToData:(NSString *)str{
    if (!str || [str length] == 0) {
        return nil;
    }
    
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    return hexData;
}

例如:字符串:1D1E0E00A12F6951AD17DF003C4E 结果:<1d1e0e00 a12f6951 ad17df00 3c4e>

将NSData转成可操作的字符串,十进制


/**
 将NSData转成可操作的字符串,十进制

 @param data nsdata
 @return 转化结果
 */
+ (NSString *)sconvertDataToHexStr:(NSData *)data
{
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    return string;
}

两个NSData进行异或计算


/**
 异或计算(XOR)

 @param sourceData 第一个
 @param keyData 第二二
 @return 结果
 */
+ (NSData *)xor_EncodeData:(NSData *)sourceData withKey:(NSData *)keyData {
    Byte *keyBytes = (Byte *)[keyData bytes]; //取关键字的Byte数组, keyBytes一直指向头部
    Byte *sourceDataPoint = (Byte *)[sourceData bytes]; //取需要加密的数据的Byte数组
    for (long i = 0; i < [sourceData length]; i++) {
        sourceDataPoint[i] = sourceDataPoint[i] ^ keyBytes[i]; //然后按位进行异或运算
    }
    return sourceData;
}

再附上几个开发过程中常用到的小方法?

MD5加密


/**
 MD5加密

 @param password 密码
 @return 加密后的密码
 */
+ (NSString *)MD5StringWithPassWord:(NSString*)password {
    if ([password isKindOfClass:[NSString class]]) {
        NSString *str = (NSString *)password;
        const char *cStr = [str UTF8String];
        unsigned char result[16];
        CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
        return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],result[8], result[9], result[10], result[11],result[12], result[13], result[14], result[15]] lowercaseString];
    }else{
        return nil;
    }
}

json字符串转成字典

/**
 json转字典

 @param jsonString json
 @return 字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err){
        NSLog(@"json解析失败:%@",err);
        return nil;
    }
    return dic;
}

将字典转json字符串


/**
 将字典转成j字符串

 @param dict 字典
 @return 字符串
 */
+ (NSString *)convertToJsonData:(NSDictionary *)dict{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

 

判断字符串是否为空


/**
 判断字符串是否为空

 @param aStr 传入的内容
 @return YES 不是字符串
 */
+ (BOOL)isEmptyOrNull:(NSString *)aStr {
    if (![aStr isKindOfClass:[NSString class]]) {
        return YES;
    }
    if (!aStr) {
        return YES;
    }
    if ([aStr isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if (!aStr.length) {
        return YES;
    }
    if (aStr == nil) {
        return YES;
    }
    if (aStr == NULL) {
        return YES;
    }
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmedStr = [aStr stringByTrimmingCharactersInSet:set];
    if (!trimmedStr.length) {
        return YES;
    }
    return NO;
}

判断数组是否为空


/**
 判断数组是否为空
 
 @param arr 数组
 @return bool
 */
+(BOOL)isEmptyArrOrNull:(NSMutableArray*)arr{
    if (![arr isKindOfClass:[NSMutableArray class]] || ![arr isKindOfClass:[NSArray class]]) {
        return YES;
    }
    if (arr == nil) {
        return YES;
    }
    if (arr.count == 0) {
        return YES;
    }
    if (arr == NULL) {
        return YES;
    }
    return NO;
}

判断字典是否为空


/**
 判断字典是否为空
 
 @param dic 数组
 @return bool
 */
+(BOOL)isEmptyDictionaryOrNull:(NSDictionary*)dic{
    if (dic == nil) {
        return YES;
    }
    if (![dic isKindOfClass:[NSDictionary class]]) {
        return YES;
    }
    if (dic.count == 0) {
        return YES;
    }
    if (dic == NULL) {
        return YES;
    }
    
    return NO;
}

判断手机是否是异形曲面屏iPhone X等,需要导入一个官方类#import <sys/utsname.h>


/**
 判断手机是否是异形屏幕
 
 @return YES 是 异形屏幕
 */
+ (BOOL)iphoneIsProfiledScreen {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString*platform = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    if([platform isEqualToString:@"iPhone10,3"] || [platform isEqualToString:@"iPhone10,6"]  || [platform isEqualToString:@"iPhone11,8"] || [platform isEqualToString:@"iPhone11,2"] || [platform isEqualToString:@"iPhone11,6"] || [platform isEqualToString:@"iPhone11,4"] ) {
        return YES;
    } else {
        return NO;
    }
}

将数组转成字符串


/**
 将数组转成字符串

 @param arrJson 数据
 @return 字符串
 */
+ (NSString *)jsonStringCompactFormatForNSArray:(NSArray *)arrJson {
    if (![arrJson isKindOfClass:[NSArray class]] || ![NSJSONSerialization isValidJSONObject:arrJson]) {
        return nil;
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrJson options:0 error:nil];
    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return strJson;
}

 

2016-11-24 15:57:17 dkq972958298 阅读数 7376

其中将十六进制字符串转换成NSData的代码如下:

- (NSData *)convertHexStrToData:(NSString *)str {
    if (!str || [str length] == 0) {
        return nil;
    }
    
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    
    LEDEBUG(@"hexdata: %@", hexData);
    return hexData;
}

将NSData转换成十六进制的字符串则可使用如下方式:


- (NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}





2015-06-09 20:44:29 love_2101 阅读数 4036
+ (NSData *) stringToHexData:(NSString *)hexStr
{
    int len = [hexStr length] / 2;    // Target length
    unsigned char *buf = malloc(len);
    unsigned char *whole_byte = buf;
    char byte_chars[3] = {'\0','\0','\0'};
    
    int i;
    for (i=0; i < [hexStr length] / 2; i++) {
        byte_chars[0] = [hexStr characterAtIndex:i*2];
        byte_chars[1] = [hexStr characterAtIndex:i*2+1];
        *whole_byte = strtol(byte_chars, NULL, 16);
        whole_byte++;
    }
    
    NSData *data = [NSData dataWithBytes:buf length:len];
    free( buf );
    return data;
}


//data转换为十六进制的string
+ (NSString *)hexStringFromData:(NSData *)myD{
    
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
        
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if([newHexStr length]==1)
            
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        
        else
            
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    NSLog(@"hex = %@",hexStr);
    
    return hexStr;
}
没有更多推荐了,返回首页