开发者

NSInteger to binary (string) value in 8bit format

Jarret Hardie (thanks !) post this code yesterday to convert a NSinteget to binary, and works perfectly,开发者_开发技巧 but i need in 8bit format:

4 -> 00000100

any ideas to modify this code?

// 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);

Thanks !!!!!!


This should work:

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


If anybody's interested, here is my version that:

  • automatically detects number of bits
  • respects Coding Guidelines for Cocoa.

Snippet:

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];
}


In reference, and in support of @vincent osinga's answer.. Here is that code, wrapped in a C-function.. that returns the binary "string" from an NSUInteger.. perfect for logging bitwise typedef's, etc.

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

I don't think NSInteger numberCopy = theNumber; is necessary as you're not using a pointer, but simply the primitive value as an argument, // so you won't change your original value. This will enable use as / yield results like...

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 */
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜