2012-07-28 18 views
0

更具體地說,我把一個斷點在我的代碼後 NSString *signStr = [NSString stringWithCString:text encoding:NSASCIIStringEncoding]; 我打電話與secret= @"123456789"movingFactor = 1 功能我注意到,在斷點處,signStr是一個空字符串, 也都存在代碼中的任何其他明顯錯誤? 由於如何在Objective-C中獲得一個字符數組的NSString等價物?

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

} 

回答

1

要成爲一個「C字符串」它必須由一個零('\0')被終止。如果movingFactor爲1,則最後一個字符將爲0x01,並且由於移位,第一個(以及每隔一個字節)爲零。這使第一個字符爲零,這使字符串「空」。

+0

那麼,我該如何讓我的代碼工作?我怎麼能修改字節的東西,然後將其轉換爲NSString具有相同的值按位? – SwiftMatt 2012-07-28 14:37:34

+1

你確定你想要一個NSString嗎?如果你需要能夠存儲任意字節,NSData似乎更適合。 – 2012-07-29 05:04:58

相關問題