将 int64 转换为 NSData

发布于 2024-07-19 05:39:03 字数 480 浏览 7 评论 0原文

我需要将 long 值从 int64 转换为 NSData,以便稍后可以对其运行哈希算法。 我执行:

int64_t longNumber = 9000000000000000000L;
NSMutableData *buffer = [NSMutableData dataWithBytes:&longNumber length:sizeof(longNumber)];

NSLog(@"%lld", [buffer bytes]);
NSLog(@"%lld", longNumber);

结果控制台输出如下:

6201314301187184 9000000000000000000

为什么 NSData 无法正确存储长数字的值? 如果我在循环中运行它,NSData 字节会漂移,从 620 开始,然后是 621 等等。 我是否通过 [buffer bytes] 输出 longNumber 的地址而不是其值?

I need to convert a long value from int64 to NSData, so I can later run a hash algorithm on it. I perform:

int64_t longNumber = 9000000000000000000L;
NSMutableData *buffer = [NSMutableData dataWithBytes:&longNumber length:sizeof(longNumber)];

NSLog(@"%lld", [buffer bytes]);
NSLog(@"%lld", longNumber);

The resultant console output is like this:

6201314301187184
9000000000000000000

Why is NSData not properly storing the value of the long number? If I run this in a loop, the NSData bytes drift, starting with 620, then 621 and on. Am I outputting the address of the longNumber via [buffer bytes] and not its value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

平安喜乐 2024-07-26 05:39:03

您有两个主要问题:首先,您的数字对于您要投射的时间来说太大了。 您应该使用 9000000000000000000LL 来表示 long long 常量,而不是 9000000000000000000L

其次,您正确回答了您的问题,您正在打印一个地址。 将您的 NSLog 行替换为以下行:

NSLog(@"%lld", *((int64_t*)[buffer bytes]));

您应该会看到您期望的结果。

You have two major issues: first, your number is too large for the long that you are casting it to. Instead of 9000000000000000000L you should have 9000000000000000000LL to indicate a long long constant.

Second, you answered your question correctly, you are printing out an address. Replace your NSLog line with with this line:

NSLog(@"%lld", *((int64_t*)[buffer bytes]));

and you should see the result you expect.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文