【问题标题】:How do obtain the NSString equivalent for an array of chars in Objective-C?如何在 Objective-C 中获取字符数组的 NSString 等效项?
【发布时间】:2012-07-28 05:35:30
【问题描述】:

更具体地说,我在代码中放置了一个断点 NSString *signStr = [NSString stringWithCString:text encoding:NSASCIIStringEncoding]; 我用secret= @"12345678901234567890"movingFactor = 1 调用函数 我注意到在断点处,signStr 是一个空字符串, 代码中还有其他明显的错误吗? 谢谢

-(NSString*) generateOTP:(NSString*) secret with:(uint64_t) movingFactor
{
    NSString* result;

    const int DIGITS = 6;
    const int SIX_DIGITS = 1000000;

    char text[8];
    for (int i = 7; i >= 0; i--) {
        text[i] = movingFactor & 0xff;
        movingFactor >>= 8;
    }

    NSString *signStr = [NSString stringWithCString:text encoding:NSASCIIStringEncoding];

    NSString* hash = [self sha1UseKey:secret toSign:signStr];

    int offset = [hash characterAtIndex:[hash length] - 1] & 0xf;

    int binary = (([hash characterAtIndex:offset] & 0x7f) << 24) |
        (([hash characterAtIndex:offset+1] & 0xff) << 16) |
        (([hash characterAtIndex:offset+2] & 0xff) << 8) | ([hash characterAtIndex:offset+3] & 0xff);

    int otp = binary % SIX_DIGITS;

    result = [NSString stringWithFormat:@"%d", otp];

    NSString* zero = @"0";
    while ([result length] < DIGITS) {
        result = [zero stringByAppendingString:result];
    }
    return result;

}

【问题讨论】:

    标签: objective-c arrays nsstring char


    【解决方案1】:

    要成为“C 字符串”,它必须以零结尾 ('\0')。如果movingFactor 为 1,那么最后一个字符将为0x01,并且第一个(以及每隔一个字节)由于移位而为零。这使得 first 字符为零,这使得字符串“空”。

    【讨论】:

    • 那么我该如何让我的代码工作呢?如何按字节修改某些内容,然后按位将其转换为具有相同值的 NSString?
    • 您确定要在这里使用 NSString 吗?如果您需要能够存储任意字节,NSData 似乎更合适。
    猜你喜欢
    • 2011-05-01
    • 2023-04-03
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    相关资源
    最近更新 更多