在NSString中存储和检索未签名的long long值 [英] Storing and retrieving unsigned long long value to/from NSString

查看:87
本文介绍了在NSString中存储和检索未签名的long long值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无符号的long long值,我想将其存储到NSString中并从字符串中检索.

I have an unsigned long long value which I want to store into an NSString and retrieve from the string.

最初,我在NSNumber中具有值,并且正在使用它来获取字符串

Initially I have the value in an NSNumber and I am using this to get the string

NSString *numStr = [NSString stringWithFormat:@"%llu", [myNum unsignedLongLongValue]];

其中myNum是一个NSNumber.

where myNum is an NSNumber.

要从NSString取回NSNumber,我必须首先获取unsigned long long值.但是NSString类中没有方法可以做到这一点(我们只有一种方法可以获取long long值,而不是无符号long long值).

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).

有人可以告诉我如何将值返回到NSNumber变量中.

Can someone please tell me how I can get back the value into an NSNumber variable.

谢谢.

推荐答案

有很多方法可以完成此操作.以下是最务实的:

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);

这做出了一些合理的假设,例如numStr将仅包含数字,并且包含有效"无符号长整型值.这种方法的缺点是UTF8String创建的内容实际上等于[[numStr dataUsingEncoding:NSUTF8StringEncoding] bytes],或者换句话说,每次调用都包含32字节的自动释放内存.对于绝大多数用途而言,这从来没有问题.

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.

有关如何将诸如unsignedLongLongValue之类的内容快速添加到NSString且不使用自动释放的内存作为副作用的示例,请查看我对此SO问题.特别是rklIntValue的示例实现,只需进行少量修改即可实现unsignedLongLongValue.

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.

有关strtoull的更多信息可以在其手册页中找到.

More information regarding strtoull can be found in its man page.

这篇关于在NSString中存储和检索未签名的long long值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆