zoukankan      html  css  js  c++  java
  • 在iOS开发中,我们会遇到十六进制和字符串之间相互转换,话不多说,直接上代码:

    //将十六进制的字符串转换成NSString则可使用如下方式:
    + (NSString *)convertHexStrToString:(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;
    }
    NSString *string = [[NSString alloc]initWithData:hexData encoding:NSUTF8StringEncoding];
    return string;
    }

    `

    //将NSString转换成十六进制的字符串则可使用如下方式:
    + (NSString *)convertStringToHexStr:(NSString *)str {
    if (!str || [str length] == 0) {
        return @"";
    }
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    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;
    }


    作者:零距离仰望星空
    链接:http://www.jianshu.com/p/12e3799cbca2
    來源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    linux | 管道符、输出重定向
    php 升级php5.5 、php7
    mysql 启动失败
    centos7.2安装phpmyadmin
    php file_get_contents失败[function.file-get-contents]: failed to open stream: HTTP request failed!解决
    go println与printf区别
    前端 head 中mate 详解
    centos 7 安装mysql
    iOS数据持久化—数据库SQLite模糊查询
    C 语言字符串和格式化输入与输出
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/7243741.html
Copyright © 2011-2022 走看看