Reputation:
I am trying to figure out how to convert an NSInteger, say 56, to an NSString that is a binary representation of the original (int) value. Perhaps someone knows a formatting technique that can accept 56 and return "111000" within Objective C. Thanks All.
Upvotes: 14
Views: 23108
Reputation: 400274
There's no built-in formatting operator to do that. If you wanted to convert it to a hexadecimal string, you could do:
NSString *str = [NSString stringWithFormat:@"%x", theNumber];
To convert it to a binary string, you'll have to build it yourself:
NSMutableString *str = [NSMutableString stringWithFormat:@""];
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1)
{
// Prepend "0" or "1", depending on the bit
[str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
}
Upvotes: 27
Reputation: 4171
Roughly:
-(void)someFunction
{
NSLog([self toBinary:input]);
}
-(NSString *)toBinary:(NSInteger)input
{
if (input == 1 || input == 0) {
return [NSString stringWithFormat:@"%d", input];
}
else {
return [NSString stringWithFormat:@"%@%d", [self toBinary:input / 2], input % 2];
}
}
Upvotes: 4
Reputation: 211
NSString * binaryStringFromInteger( int number )
{
NSMutableString * string = [[NSMutableString alloc] init];
int spacing = pow( 2, 3 );
int width = ( sizeof( number ) ) * spacing;
int binaryDigit = 0;
int integer = number;
while( binaryDigit < width )
{
binaryDigit++;
[string insertString:( (integer & 1) ? @"1" : @"0" )atIndex:0];
if( binaryDigit % spacing == 0 && binaryDigit != width )
{
[string insertString:@" " atIndex:0];
}
integer = integer >> 1;
}
return string;
}
I started from Adam Rosenfield's version, and modified to:
Sample output:
-7 11111111 11111111 11111111 11111001
7 00000000 00000000 00000000 00000111
-1 11111111 11111111 11111111 11111111
2147483647 01111111 11111111 11111111 11111111
-2147483648 10000000 00000000 00000000 00000000
0 00000000 00000000 00000000 00000000
2 00000000 00000000 00000000 00000010
-2 11111111 11111111 11111111 11111110
Upvotes: 21