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.
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.
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.
NSString * num = @"123456";
NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc]init];
NSNumber * number = [numberFormatter numberFromString:num];
unsigned long long valueUInt64 = number.unsignedLongLongValue;
long
is 32 bits (on most platforms). To ensure that one is getting a 64 bit value, the long long
type exists. To get the unsigned version, one simply prefaces the type with unsigned
, as is done for any integer type.
@"18446744073709551615"
(that is the maximum unsigned long long
value). It is not immediately clear whether this is a bug or feature of NSNumberFormatter
. The answer by @Tommy works correctly in this scenario.
You can use strtoull(const char *, char **, int)
as following:
NSString *value = @"1234567";
UInt64 convertedValue = strtoull([value UTF8String], NULL, 0);
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]);