Alexandru
Alexandru

Reputation: 12882

NSString to UInt64

How do you convert from NSString to UInt64?

For example, something like this if a UInt64Value helper method existed:

NSString *value = @"1234567";
UInt64 convertedValue = [value UInt64Value];

I am trying to do this in an iOS project.

Upvotes: 5

Views: 3038

Answers (4)

Tom Zhang
Tom Zhang

Reputation: 1

You can use strtoull(const char *, char **, int) as following:

NSString *value = @"1234567";
UInt64 convertedValue = strtoull([value UTF8String], NULL, 0);

Upvotes: 0

Tommy
Tommy

Reputation: 100622

To pitch another possibility for completeness:

NSScanner *scanner = [NSScanner scannerWithString:value];
unsigned long long convertedValue = 0;
[scanner scanUnsignedLongLong:&convertedValue];
return convertedValue;

... check the result on scanUnsignedLongLong if you want to differentiate between finding a value of 0 and finding something that isn't a number.

Upvotes: 10

Haroldo Gondim
Haroldo Gondim

Reputation: 7995

You can get a UInt64 with longLongValue

NSString *str = @"23147653105732";
UInt64 uint64 = [str longLongValue];

Another way to get an int64 is:

NSString *str = @"23147653105732";
int64_t int64_t = atoll([str UTF8String]);

Upvotes: -1

Muhammad Zohaib Ehsan
Muhammad Zohaib Ehsan

Reputation: 931

NSString * num = @"123456";

NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc]init];
NSNumber *  number = [numberFormatter numberFromString:num];
unsigned long long valueUInt64 = number.unsignedLongLongValue;

Upvotes: 5

Related Questions