简体   繁体   中英

iOS Obj-C Equivalent to JavaScript's toString(16)

I am trying to generate a hex id string from a random number. In JavaScript I do:

var id = ( Math.random() * Math.pow(10, 17) + Math.random() * Math.pow(10, 17) + Math.random() * Math.pow(10, 17) + Math.random() * Math.pow(10, 17) ).toString(16);

The result is a random id like: "2d50e9b4835d7e0".

Is anyone aware of a similar method in iOS that I could use to do the same thing? I'd like the result of the iOS call to return a string of the same length (15 chars).

You can get random number in Objective C using following code

-(int)getRandomNumberBetween:(int)from to:(int)to {

    return (int)from + arc4random() % (to-from+1);
}

Edit I have changed this method in order to get hex string

- (NSString *)getHexString
{   
    NSString *longlongstr = [NSString stringWithFormat:@"%d%d%d%d%d%d",[self getRandomNumberBetween:100 to:999],[self getRandomNumberBetween:100 to:999],[self getRandomNumberBetween:100 to:999],[self getRandomNumberBetween:100 to:999],[self getRandomNumberBetween:100 to:999],[self getRandomNumberBetween:100 to:999]];
    long long longnumber = [longlongstr longLongValue];
    NSString *hexStr =  [NSString stringWithFormat:@"%llx",longnumber];
    NSLog(@"%@",hexStr);
     return hexStr;

}

So your code would look something like

NSString *hexStr = [self getHexString];

You can modify it as per your needs it gives you 15 digit hexa decimal value

I found a solution to this:

#define cPow pow(3, 19)

long long val = ((
    rand() * cPow +
    rand() * cPow +
    rand() * cPow +
    rand() * cPow
));

NSString *newId = [[NSString alloc] initWithFormat:@"%llx", val];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM