Created
November 9, 2015 22:27
-
-
Save garmstro/f78748046a56b23e3d5d to your computer and use it in GitHub Desktop.
NSNumber Extensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSInteger+NSIntegerExtensions.h | |
// IntegerFunctions | |
// | |
// Created by Geoff Armstrong on 10/30/15. | |
// Copyright © 2015 Geoff Armstrong. All rights reserved. | |
// | |
#ifndef NSNumber_NSNumberExtensions_h | |
#define NSNumber_NSNumberExtensions_h | |
@interface NSNumber (NSIntegerExtensions) | |
- (NSString *) integerToString; | |
- (int) countOnesInBinaryInteger; | |
@end | |
#endif /* NSInteger_NSIntegerExtensions_h */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSInteger+NSIntegerExtensions.m | |
// IntegerFunctions | |
// | |
// Created by Geoff Armstrong on 10/30/15. | |
// Copyright © 2015 Geoff Armstrong. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
#import "NSNumber+NSNumberExtensions.h" | |
#define asciiShift 48 | |
@implementation NSNumber (NSIntegerExtensions) | |
- (NSString *) integerToString { | |
BOOL isNegative = NO; | |
NSInteger theInteger = [self integerValue]; | |
NSMutableString *theString = [[NSMutableString alloc] init]; | |
//Check to see if the integer is negative | |
if ([self integerValue] < 0) { | |
isNegative = YES; | |
theInteger *= -1; | |
} | |
//Cycle through the digits of the integer | |
while (theInteger > 0) { | |
int digit = theInteger % 10; | |
unichar character = (unichar) digit + asciiShift; | |
[theString insertString:[NSString stringWithCharacters:&character length:1] atIndex:0]; | |
theInteger /= 10; | |
} | |
if (isNegative) { | |
unichar character = '-'; | |
[theString insertString:[NSString stringWithCharacters:&character length:1] atIndex:0]; | |
} | |
return theString; | |
} | |
- (int) countOnesInBinaryInteger { | |
BOOL isNegative = NO; | |
int count = 0; | |
NSInteger theInteger = [self integerValue]; | |
//Check to see if the integer is negative | |
if ([self integerValue] < 0) { | |
isNegative = YES; | |
theInteger *= -1; | |
} | |
while (theInteger > 0) { | |
int digit = theInteger % 2; | |
if (digit) { | |
count++; | |
} | |
//Bitshift integer to the right (equivalent to divide by 2) | |
theInteger >>= 1; | |
} | |
//Add negative bit? | |
if (isNegative) { | |
count++; | |
} | |
return count; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment