十六进制和字符串的相互转换

时间:2021-06-30 17:50:54


1.字符串转换十六进制   比如 FF ->0XFF

NSData* convert(NSString* str){
    
    const char* cs = str.UTF8String;
    
    int count = (int)strlen(cs);
    int8_t  bytes[count / 2];
    for(int i = 0; i<count; i+=2){
        char c1 = *(cs + i);
        char c2 = *(cs + i + 1);
        if(C2I(c1) >= 0 && C2I(c2) >= 0){
            bytes[i / 2] = C2I(c1) * 16 + C2I(c2);
            
        }else{
            return nil;
        }
    }
    return [NSData dataWithBytes:bytes length:count /2];
}


2.十六进制转换十进制  比如 0x37 -> 55


-(NSString *)stringForData1:(NSData *)data{
    uint8_t* a = (uint8_t*) [data bytes];
    NSString *str=[NSString stringWithFormat:@"%d",*a];
    return str;
}

3.十六进制转换字符串 比如 0XFF ->FF

NSString *newHexStr = [NSString stringWithFormat:@"%0.2X",0xff&0xff];