Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

subo

macrumors newbie
Original poster
Jan 11, 2010
5
0
Hello,
Does anyone has some code in objective-c to convert a NSString or NSInteger to Binary representation string?
Thanks All.

Example:

hello -> 01101000 01100101 01101100 01101100 01101111
 
For an NSString, see the function -(const char *)UTF8String.

From here, there would be a LOT of different ways to turn a single 8-bit integer into binary.


Brute force:

Code:
char * CharToBinary( const char input )
{
	char binary[] = "00000000"; //< bug, since this will be deallocated on return.

	if ( input & 0x80 )
		binary[0] = '1';

	if ( input & 0x40 )
		binary[1] = '1';

	if ( input & 0x20 )
		binary[2] = '1';

	if ( input & 0x10 )
		binary[3] = '1';

	if ( input & 0x08 )
		binary[4] = '1';

	if ( input & 0x04 )
		binary[5] = '1';

	if ( input & 0x02 )
		binary[6] = '1';

	if ( input & 0x01 )
		binary[7] = '1';

	return binary;
}

This is probably about the worst way you can do it, since it includes a lot of branches, but it can give you an idea of where you might go with a better-implemented function--e.g. a for loop or a recursive function.
 
Here's one I wrote a while ago that prints out a string representation of a integer value (will be twice as big for a 64-bit number) with some optional box doodads drawn in.

Code:
-(NSString*)binaryStringRepresentation:(NSInteger)input drawBoxes:(BOOL)shouldDrawBoxes {
	NSMutableString *s = [NSMutableString string];
	NSInteger i = 0;
	NSInteger mask = 0;
	NSInteger bits;
	
	#if __LP64__
		bits = 64;
	#else
		bits = 32;
	#endif
	
	if (shouldDrawBoxes) {
		for (i = 0; i < bits / 8; i++) {
			[s appendString:@"+--------"];
		}
		[s appendString:@"+\n"];
	}
	
	for (i = 0; i < bits; i++) {
		if (i % 8 == 0) {
			if (shouldDrawBoxes) {
				[s appendString:@"|"];
			} else {
				if (i > 1) {
					[s appendString:@" "];
				}
			}
		}
		mask = 0x1 << ((bits - 1) - i);
		if (input & mask) {
			[s appendString:@"1"];
		} else {
			[s appendString:@"0"];
		}
	}
	
	if (shouldDrawBoxes) {
		[s appendString:@"|\n"];
		for (i = 0; i < bits / 8; i++) {
			[s appendString:@"+--------"];
		}
		[s appendString:@"+\n"];
	}
	
	return s;
}

Which will produce a string something like this:

Code:
+--------+--------+--------+--------+
|00100010|10100101|11110000|00001111|
+--------+--------+--------+--------+
 
Hey, sorry, I didn't understand you wanted to start with a character string...my function only shows integer values, so you'd have to walk the string and convert each character to use it, oh well. That's what I get for not reading carefully.
 
Code:
#if __LP64__
	bits = 64;
#else
	bits = 32;
#endif
Wouldn't it be better to use sizeof(input) * 8? :)
 
Very nice function and it calculates the correct value :)
I use NSInteger bits = sizeof(input)*8; instead of
NSInteger bits;

#if __LP64__
bits = 64;
#else
bits = 32;
#endif

Thank you!
 
You can use the same code for NSString as for NSInteger, like this:
Code:
- (NSString *)bits:(NSInteger)value forSize:(int)size {
    const int shift = 8*size - 1;
    const unsigned mask = 1 << shift;
    NSMutableString *result = [NSMutableString string];
    for (int i = 1; i <= shift + 1; i++ ) {
        [result appendString:(value & mask ? @"1" : @"0")];
        value <<= 1;
        if (i % 8 == 0) {
            [result appendString:@" "];
        }
    }
    return result;
}

- (NSString *)bitsForInteger:(NSInteger)value {
    return [self bits:value forSize:sizeof(NSInteger)];
}

- (NSString *)bitsForString:(NSString *)value {
    const char *cString = [value UTF8String];
    int length = strlen(cString);
    NSMutableString *result = [NSMutableString string];
    for (int i = 0; i < length; i++) {
        [result appendString:[self bits:*cString++ forSize:sizeof(char)]];
    }
    return result;
}
 
plinden, i fix some syntax warnings and it's working.
Thank you!
 
Doh, sorry about the syntax errors - I converted from a couple of C functions and didn't fix the method signatures properly. I've corrected the code and made the method names a bit more Apple-y.

I'm not an Objective C programmer, I'm just dipping into it to learn something new.
 
Very nice function and it calculates the correct value :)
I use NSInteger bits = sizeof(input)*8; instead of
NSInteger bits;

#if __LP64__
bits = 64;
#else
bits = 32;
#endif

Thank you!

Why guess when you can query the header "NSObjCRuntime" for the information needed?

I'm to lazy to write it all out but here is the code to print an NSInteger as binary.

Code:
    NSInteger  number  = 0xAAAA;

    NSUInteger  bit     = ~(NSUIntegerMax >> 1);

    do
    {
        printf("%c", (((NSUInteger)number & bit) ? '1' : '0'));
    } while ( bit >>= 1 );
 
Did it anyway.

Code:
#import <Cocoa/Cocoa.h>

NSString* stringCreateWithNSInteger(NSInteger number)
{
    NSMutableString*    string  = [[NSMutableString string] retain];
    NSUInteger          bit     = ~(NSUIntegerMax >> 1);

    do
    {
        [string appendString:(((NSUInteger)number & bit) ? @"1" : @"0")];
    } while ( bit >>= 1 );

    return string;
}

int main(int argc, const char* argv[])
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    NSInteger   number = 0xDEADBEEF;
    NSString*   string = stringCreateWithNSInteger(number);
    NSLog(@"%X = %@", number, string);
    
    [string release];

    [pool release];
    
    return 0;
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.