【问题标题】:NSUInteger on 64 and 32 bit architectures64 位和 32 位架构上的 NSUInteger
【发布时间】:2015-09-14 20:21:21
【问题描述】:

我实现了FNV1a哈希算法如下:

#import "SWBHashAlgorithm.h"

@implementation SWBHashAlgorithm
- (NSUInteger)hashValues:(NSString *)values withSalt:(NSString *)salt {
    const NSUInteger FnvPrime = 16777619;
    const NSUInteger FnvOffsetBasis = 2166136261;

    NSMutableString *input = [[NSMutableString alloc]init];
    [input appendString:values];
    if (salt != nil && ![salt isEqual:[NSNull null]]) {
        [input appendString:salt];
    }
    NSUInteger hash = FnvOffsetBasis;

    for (NSInteger i = 0; i != [input length]; ++i) {
        hash = (hash ^ [input characterAtIndex:i]) * FnvPrime;
    }
    return hash;
}

@end

在 x86_64 架构上,我的单​​元测试通过了:

- (void)testSomeData {
    // Arrange

    // Act
    NSUInteger result = [self.hashAlgorithm hashValues:@"value1value2" withSalt:@"salt"];

    // Assert
    XCTAssertEqual(result, 4989295659699749532); }

但在 i386 上它失败了,因为:

SWBHashAlgorithmTests.m:36:((结果)等于(4989295659699749532)) 失败:(“3553444508”)不等于(“4989295659699749532”):33
NSUInteger 结果 = [self.hashAlgorithm hashValues:@"value1value2" withSalt:@"salt"]; 34 35 // 断言 36
XCTAssertEqual(结果,4989295659699749532); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 37 } 38

如何在 32 位架构中获得相同的值?

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    NS(U)Integer 在 32/64 位环境下有不同的类型声明。

    来自 64 位转换指南

    这些变化中最值得注意的是 NSInteger 和 NSUInteger(Cocoa 数据类型)在 64 位环境中为 64 位,在 32 位环境中为 32 位。

    要在两种环境中获得相同的结果,请使用固定大小,例如 uint32_tuint64_t

    【讨论】:

    • 非常感谢!这很快。
    猜你喜欢
    • 1970-01-01
    • 2013-12-19
    • 2011-12-18
    • 2014-12-17
    • 1970-01-01
    • 2011-04-05
    • 2017-05-12
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多