Problems converting NSString to unsigned long long [duplicate] - objective-c

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Storing and retrieving unsigned long long value to/from NSString
Having problems trying to convert an NSString to an unsigned long long. Heres the code:
NSString* mp3id = [[NSString alloc] initWithUTF8String:"16902439379132728577"];
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
NSNumber* persistentId = [f numberFromString:mp3id];
unsigned long long test = [persistentId unsignedLongLongValue];
NSLog(#"unsigned long long is %llu",test);
[f release];
Output:
2011-07-09 15:28:06.834 NBUnityMP3Plugin[443:307] unsigned long long is 16902439379132729344
2011-07-09 15:28:06.847 NBUnityMP3Plugin[443:307] persistant id is 1.690243937913273e+19
To make it clearner:
16902439379132728577 - input
16902439379132729344 - output
Ideally I would like to get that unsigned long long into an NSNumber variable. I figured that would be easy if I only had an unsigned long long.

NSNumberFormatter is representing the unsigned long long as a float, and I thought setting [f setAllowsFloats:NO]; after initializing the NSNumberFormatter would fix the problem. It doesn't seem to do that, though (returning nil when trying to set the number). It is possible that 16902439379132728577 is too long for NSNumberFormatter to handle as an integer, and it may only handle signed integers in the long long range.

Related

NSString intValue deforming actual number

I was making a basic method that takes a Flickr image URL and returns the image's ID.
I'm passing the method the NSString #"http://farm6.staticflickr.com/5183/5629026092_c6762a118f".
The goal is to return the int: 5629026092, which is in the image's URL and is the image's ID.
Here is my method:
-(int)getImageIDFromFlickrURL:(NSString *)imageURL{
NSArray *objectsInURLArray = [imageURL componentsSeparatedByString:#"/"];
NSString *lastObjectInFlickrArray = [objectsInURLArray lastObject];
NSArray *dirtyFlickrIdArray = [lastObjectInFlickrArray componentsSeparatedByString:#"_"];
NSString *flickIDString = [dirtyFlickrIdArray objectAtIndex:0];
NSLog(#"flickr id string: %#",flickIDString);
int flickrID = [flickIDString intValue];
NSLog(#"id: %i",flickrID);
return flickrID;
}
The output in the console is:
2012-05-26 13:30:25.771 TestApp[1744:f803] flickr id string: 5629026092
2012-05-26 13:30:25.773 TestApp[1744:f803] id: 2147483647
Why is calling intValue deforming the actual number?
Use long long instead, your number is greater than int can handle (max being 2147483647 as you can see in your second log)
Your value is too big to represent in 32 bits. The biggest value you can store in a signed 32 bit integer (int) is 2147483647. For unsigned ints, it's 4294967295. You need to convert to a long long integer to represent a number as big as 5629026092.
You'll probably need to create a number formatter for that. I'm no expert on number formatters, and always have to dig out the documentation to figure out how to use them.
I just tried it, and this code works:
NSString *numberString = #"5629026092";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *number = [formatter numberFromString: numberString];
long long value = [number longLongValue];
NSLog(#"%# = %qi", numberString, value);
[formatter release];
You could also convert the string to a C string and use scanf, come to think of it.
Easy ^^: INT_MAX Maximum value for a variable of type int. 2147483647
I found this to be a convenient way to do it:
NSString *flickIDString = [dirtyFlickrIdArray objectAtIndex:0]; // read some huge number into a string
// read into a NSNumber object or a long long variable. you choose
NSNumber *flickIDNumber = flickIDString.longLongValue;
long long flickIDLong = flickIDString.longLongValue;

Get a long value from an NSString

I need to get a long value from an NSString.
For example, I have this:
NSString *test = #"5437128";
and I need :
long myLong = 5437128;
How I can get this long value from the NSString?
Thank you, it will help me!
long longVariable = [test longLongValue];
See NSString documentation..
Use the NSScanner like in the following code:
unsigned x;
[[NSScanner scannerWithString: s2] scanHexInt: &x];
when typing the scanHexInt stop at scan and see yourself which one you need - there are many possibilities to get values from strings....
You might want to use scanlonglong... having declared your variable as long
use this code :
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
long number = [[numberFormatter numberFromString:string] longValue];
[numberFormatter release];
i use the following in case you don't want to lose the fractions value of your number
double x =[stringValue doubleValue];
instead of
double x = [stringValue longLongValue];
if we assume that we have the following string value
and we want to convert it to double we have 2 ways
NSString * stringValue = #"31.211529225111";
way #1
double x = [stringValue longLongValue];
result will be : x = 31
way #2
double x =[stringValue doubleValue];
result will be : x = 31.211529225111001

Strange hex formatting in NSString

Try this:
unsigned long long int N; = 23229877463LL;
NSString* s = [NSString stringWithFormat:#"dec:%qi, hex:%qX",N,N];
NSLog(#"output: %#",s);
output: dec:23229877460, hex:689BCCD400000005
What's up with the 00000005??? In mySQL, hex(23229877460) = 5689BCCD4. Also, every other language seems to do this correctly. A 16 digit long hex is like 4 gazillion (16^16), right?
How can I get objective-c to format hex numbers that other languages can understand?
After fixing the spurious ; to yield:
unsigned long long int N = 23229877463LL;
NSString* s = [NSString stringWithFormat:#"dec:%qi, hex:%qX",N,N];
NSLog(#"output: %#",s);
The code works exactly as expected:
2011-01-09 10:46:16.236 dfjkdfkjfdjkfd[25716:a0f] output: dec:23229877463, hex:5689BCCD7
There is something else wrong. You'll need to post more code. The line used to compile the file would probably be helpful, too.
And for giggles:
unsigned long long int N = 23229877460LL;
NSString* s = [NSString stringWithFormat:#"dec:%qi, hex:%qX",N,N];
2011-01-09 10:49:10.425 dfjkdfkjfdjkfd[25755:a0f] output: dec:23229877460, hex:5689BCCD4

NSString to NSUInteger

I've got a number in a NSString #"15". I want to convert this to NSUInteger, but I don't know how to do that...
NSString *str = #"15";
// Extract an integer number, returns 0 if there's no valid number at the start of the string.
NSInteger i = [str integerValue];
If you really want an NSUInteger, just cast it, but you may want to test the value beforehand.
The currently chosen answer is incorrect for NSUInteger. As Corey Floyd points out a comment on the selected answer this won't work if the value is larger than INT_MAX. A better way of doing this is to use NSNumber and then using one of the methods on NSNumber to retrieve the type you're interested in, e.g.:
NSString *str = #"15"; // Or whatever value you want
NSNumber *number = [NSNumber numberWithLongLong: str.longLongValue];
NSUInteger value = number.unsignedIntegerValue;
All these answers are wrong on a 64-bit system.
NSScanner *scanner = [NSScanner scannerWithString:#"15"];
unsigned long long ull;
if (![scanner scanUnsignedLongLong:&ull]) {
ull = 0; // Or handle failure some other way
}
return (NSUInteger)ull; // This happens to work because NSUInteger is the same as unsigned long long at the moment.
Test with 9223372036854775808, which won't fit in a signed long long.
you can try with [string longLongValue] or [string intValue]..

Storing and retrieving unsigned long long value to/from NSString

I have an unsigned long long value which I want to store into an NSString and retrieve from the string.
Initially I have the value in an NSNumber and I am using this to get the string
NSString *numStr = [NSString stringWithFormat:#"%llu", [myNum unsignedLongLongValue]];
where myNum is an NSNumber.
To get back the NSNumber from the NSString I have to first get the unsigned long long value. But there is no method in the NSString class to do that (we just have one for getting the long long value, not the unsigned long long value).
Can someone please tell me how I can get back the value into an NSNumber variable.
Thanks.
There are a lot of ways to accomplish this. The following is the most pragmatic:
NSString *numStr = [NSString stringWithFormat:#"%llu", [myNum unsignedLongLongValue]];
// .. code and time in between when numStr was created
// .. and now needs to be converted back to a long long.
// .. Therefore, numStr used below does not imply the same numStr above.
unsigned long long ullvalue = strtoull([numStr UTF8String], NULL, 0);
This makes a few reasonable assumptions such as numStr will only contain numeric digits and it contains a 'valid' unsigned long long value. A drawback to this approach is that UTF8String creates what essentially amounts to [[numStr dataUsingEncoding:NSUTF8StringEncoding] bytes], or in other words something along the lines of 32 bytes of autoreleased memory per call. For the vast majority of uses, this is no problem what-so-ever.
For an example of how to add something like unsignedLongLongValue to NSString that is both very fast and uses no autoreleased memory as a side effect, take a look at the end of my (long) answer to this SO question. Specifically the example implementation of rklIntValue, which would require only trivial modifications to implement unsignedLongLongValue.
More information regarding strtoull can be found in its man page.