1

Say I start with:

uint8_t x = 0x12;

For debugging purposes I want to "print" it in binary (using NSLog) so I see: 000010010.

Is there a way to do that in Objective-C? The closest I got is using %o format, which gives 22 and then manually translate that to binary.

Also what about uint16_t y = 0x1234; or uint32_t z = 0x12345678; ?

Drew McGowen
  • 11,471
  • 1
  • 31
  • 57
RobertL
  • 14,214
  • 11
  • 38
  • 44
  • Do [this](http://stackoverflow.com/questions/6373093/how-to-print-binary-number-via-printf). – ahruss Jul 29 '14 at 19:00

1 Answers1

1

Something like this should work fine:

- (void)printIntInBinary:(int)num {
    NSMutableString *binaryResult = [[NSMutableString alloc] init];
    while(num) {
        [binaryResult insertString:num&1?@"1":@"0" atIndex:0];
        num>>=1;
    }
    NSLog(@"%@",binaryResult);
}

Works for all the examples you posted!

username tbd
  • 9,152
  • 1
  • 20
  • 35
  • Thanks! Nice and simple but it doesn't print the leading zeroes. The while loop stops before inserting them. – RobertL Jul 30 '14 at 02:04