2

好的,尽管我仍然遇到问题,但我要完成的工作相当简单。

这是我的代码:

- (NSString*)toBin:(long)dec
{
    long num = dec;
    NSString *res = [NSString string];

    for (long i=63; i>=0; i--)
    {
        long div = 1<<i;
        if ((num&div)==div) res = [res stringByAppendingString:@"1"];
        else res = [res stringByAppendingString:@"0"];
    }

    return res;
}

这就是我测试它的方式:

    for (long i=1; i<10; i++)
    {
        NSLog(@"%u = %@",i,[self toBin:(long)i]);
    }

但是,上面的输出是:

1 = 0000000000000000000000000000000100000000000000000000000000000001
2 = 0000000000000000000000000000001000000000000000000000000000000010
3 = 0000000000000000000000000000001100000000000000000000000000000011
4 = 0000000000000000000000000000010000000000000000000000000000000100
5 = 0000000000000000000000000000010100000000000000000000000000000101
6 = 0000000000000000000000000000011000000000000000000000000000000110
7 = 0000000000000000000000000000011100000000000000000000000000000111
8 = 0000000000000000000000000000100000000000000000000000000000001000
9 = 0000000000000000000000000000100100000000000000000000000000001001

所以,它几乎是正确的(至于最后 32 位),尽管它似乎在前 32 位上复制了自己。我猜这与我的long体型有关,但sizeof(long)返回8. 有任何想法吗?

4

1 回答 1

5

这个表达式:

long div= 1<<i;

是一个整数,而不是一个长整数。所以你得到一个只有 32 位的整数(如果我只为我的机器说话,请原谅)。所以只需生成一个 64 位表达式:

long div = 1l<<i;
于 2012-12-09T18:36:31.747 回答