美文网首页
进制转换和随机字符串

进制转换和随机字符串

作者: Z了个L | 来源:发表于2016-10-26 14:57 被阅读14次
    
    // 随机返回一个字符串(16进制数据)
    - (NSString *)randomStr {
        NSString *string = [[NSString alloc] init];
        
        for (int i = 0; i < 16; i++) {
            int number = arc4random() % 36;
            if (number < 10) {
                int figure = arc4random() % 10;
                NSString *tempString = [NSString stringWithFormat:@"%d", figure];
                string = [string stringByAppendingString:tempString];
            }else {
                int figure = (arc4random() % 6) + 97;
                char character = figure;
                NSString *tempString = [NSString stringWithFormat:@"%c", character];
                string = [string stringByAppendingString:tempString];
            }
        }
        return string;
    }
    
    // 将十进制转化为十六进制
    - (NSString *)ToHex:(int)tmpid {
        NSString *nLetterValue;
        NSString *str =@"";
        int ttmpig;
        for (int i = 0; i<9; i++) {
            ttmpig=tmpid%16;
            tmpid=tmpid/16;
            switch (ttmpig)
            {
                case 10:
                    nLetterValue =@"A";break;
                case 11:
                    nLetterValue =@"B";break;
                case 12:
                    nLetterValue =@"C";break;
                case 13:
                    nLetterValue =@"D";break;
                case 14:
                    nLetterValue =@"E";break;
                case 15:
                    nLetterValue =@"F";break;
                default:
                    nLetterValue = [NSString stringWithFormat:@"%u",ttmpig];
                    
            }
            str = [nLetterValue stringByAppendingString:str];
            if (tmpid == 0) {
                break;
            }
        }
        if(str.length == 1){
            return [NSString stringWithFormat:@"0%@",str];
        }else{
            return str;
        }
    }
    
    
    

    相关文章

      网友评论

          本文标题:进制转换和随机字符串

          本文链接:https://www.haomeiwen.com/subject/kugduttx.html