2015-12-31 15:55:33 iOSbird 阅读数 471

将16进制字符串转换成16进制数,返回NSData类型的数据


- (NSData *)transformSignString:(NSString *)hexString{


    int j=0;

    NSInteger desLength = hexString.length/2;

    if (hexString.length%2 != 0) {

        

        return nil;

    }

    Byte bytes[desLength]; ///3ds keyByte 数组, 128

    for(int i=0;i<[hexString length];i++)

    {

        int int_ch; /// 两位16进制数转化后的10进制数

        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*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 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)

        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);

        bytes[j] = int_ch;  ///将转化后的数放入Byte数组里

        j++;

    }

    NSData *newData = [[NSData alloc] initWithBytes:bytes length:desLength];

    NSLog(@"newData=%@",newData);

    return newData;

}

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

 

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

第一个就是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;
}

 

2015-04-21 08:56:48 u013250412 阅读数 890

1.

int a = 0xff0550;


NSLog(@"a==%i",a);

    

NSString *str = @"0xff0550";


//先以16为参数告诉strtoul字符串参数表示16进制数字,然后使用0x%X转为数字类型

unsigned long red = strtoul([str UTF8String],0,16);

//strtoul如果传入的字符开头是“0x”,那么第三个参数是0,也是会转为十六进制的,这样写也可以:

    

NSLog(@"red转换完的数字为:%lu",red);


2.

//宏定义

#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]


//  示例

NSString *a = @"#FFFEE0";

NSString *aStr = [a stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];

//  NSLog(@"astr==%d",[aStr  UTF8String]);

    

UIImageView *btnImg = [[UIImageView alloc] init];

btnImg.backgroundColor = UIColorFromRGB(strtoul([aStr UTF8String],0,16));




2017-06-08 16:15:39 csdn2314 阅读数 621

原文链接

NSString *str = @"0xff055008";
//先以16为参数告诉strtoul字符串参数表示16进制数字,然后使用0x%X转为数字类型
unsigned long red = strtoul([str UTF8String],0,16);
//strtoul如果传入的字符开头是“0x”,那么第三个参数是0,也是会转为十六进制的,这样写也可以:
unsigned long red = strtoul([@"0x6587" UTF8String],0,0);
NSLog(@"转换完的数字为:%lx",red);

十六进制转换为普通字符串的。

+ (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] autorelease]; 
        [scanner scanHexInt:&anInt]; 
        myBuffer[i / 2] = (char)anInt; 
    } 
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4]; 
    NSLog(@"------字符串=======%@",unicodeString); 
    return unicodeString; 
} 

普通字符串转换为十六进制的。

+ (NSString *)hexStringFromString:(NSString *)string{ 
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding]; 
    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]; 
    } 
    return hexStr; 
}

int 转data

int i = 1; 
NSData *data = [NSData dataWithBytes: &i length: sizeof(i)]; 

data 转int

int i; 
[data getBytes: &i length: sizeof(i)];
2015-11-14 09:21:19 qq_30402119 阅读数 2649

“#ffffff”类型的十六进制字符串转换成数字
分段截取计算UIColor的RGB 直接返回颜色

传入字符串后分段截取调用字符串转换Int的方法

- (UIColor *)getColor:(NSString *)hexColor {
    NSString *string = [hexColor substringFromIndex:1];//去掉#号
    unsigned int red,green,blue;
    NSRange range;
    range.length = 2;

    range.location = 0;
    /* 调用下面的方法处理字符串 */
    red = [self stringToInt:[string substringWithRange:range]];

    range.location = 2;
    green = [self stringToInt:[string substringWithRange:range]];
    range.location = 4;
    blue = [self stringToInt:[string substringWithRange:range]];

    return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
}

截取后的字符串处理

- (int)stringToInt:(NSString *)string {

    unichar hex_char1 = [string characterAtIndex:0]; /* 两位16进制数中的第一位(高位*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 */
    unichar hex_char2 = [string characterAtIndex:1]; /* 两位16进制数中的第二位(低位) */
    int int_ch2;
    if (hex_char2 >= '0' && hex_char2 <='9')
        int_ch2 = (hex_char2 - 48); /* 0 的Ascll - 48 */
    else if (hex_char1 >= 'A' && hex_char1 <= 'F')
        int_ch2 = hex_char2 - 55; /* A 的Ascll - 65 */
    else
        int_ch2 = hex_char2 - 87; /* a 的Ascll - 97 */
    return int_ch1+int_ch2;
}

方法使用

/* 直接调用即可 */
self.backgroundColor = [self getColor:@"#ff5c6f"];

iOS网络数据安全

阅读数 622

没有更多推荐了,返回首页