NSInteger以8位格式表示二进制(字符串)值

时间:2009-12-17 08:20:52

标签: objective-c iphone binary

Jarret Hardie(谢谢!)昨天发布此代码将NSinteget转换为二进制,并且工作正常,但我需要8位格式:

4 - > 00000100

修改此代码的任何想法?

// Original author Adam Rosenfield... SO Question 655792
NSInteger theNumber = 56;
NSMutableString *str = [NSMutableString string];
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1)
{
    // Prepend "0" or "1", depending on the bit
    [str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
}

NSLog(@"Binary version: %@", str);

谢谢!!!!!!

3 个答案:

答案 0 :(得分:12)

这应该有效:

NSInteger theNumber = 56;
NSMutableString *str = [NSMutableString string];
NSInteger numberCopy = theNumber; // so you won't change your original value
for(NSInteger i = 0; i < 8 ; i++) {
    // Prepend "0" or "1", depending on the bit
    [str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
    numberCopy >>= 1;
}

NSLog(@"Binary version: %@", str);

答案 1 :(得分:5)

如果有人感兴趣,这是我的版本:

段:

NSString *NSStringWithBits(int64_t mask) {
    NSMutableString *mutableStringWithBits = [NSMutableString new];
    for (int8_t bitIndex = 0; bitIndex < sizeof(mask) * 8; bitIndex++) {
        [mutableStringWithBits insertString:mask & 1 ? @"1" : @"0" atIndex:0];
        mask >>= 1;
    }
    return [mutableStringWithBits copy];
}

答案 2 :(得分:3)

参考,并支持@vincent osinga的答案..这是代码,包含在一个C函数..从NSUInteger返回二进制“字符串”..完美的记录按位typedef's等< / p>

- (NSString*) bitString:(NSUInteger) mask{
    NSString *str = @"";
    for (NSUInteger i = 0; i < 8 ; i++) {
      // Prepend "0" or "1", depending on the bit
      str = [NSString stringWithFormat:@"%@%@", 
                      mask & 1 ? @"1" : @"0", str];
      mask >>= 1;
    }
    return str;
}

我没有认为 NSInteger numberCopy = theNumber;是必要的,因为你没有使用指针,只是将原始值作为参数// so you won't change your original value。这将使用as / yield结果,如...

NSEventType anEvent = NSLeftMouseUp|NSLeftMouseDown;
NSLog(@"%@, %u\n%@, %u\n%@, %u\n%@, %u", 
    bitString( NSScrollWheel), NSScrollWheel,
    bitString( NSLeftMouseUp|NSLeftMouseDown),
               NSLeftMouseUp|NSLeftMouseDown, 
    bitString( anEvent ), anEvent, 
    bitString( NSAnyEventMask ), NSAnyEventMask);

NSLOG➞

00010110, 22  /* NSScrollWheel */
00000011, 3   /* NSLeftMouseUp | NSLeftMouseDown */
00000011, 3   /* same results with typedef'ed variable */
11111111, 4294967295  /* NSAnyEventMask */