[英]Decimal to Binary conversion method Objective-C
您好我正在尝试在Objective-C中创建一个十进制到二进制数字转换器但是已经不成功了...到目前为止,我有以下方法,这是一种尝试从Java转换为类似的方法。 任何帮助使这种方法工作非常感谢。
+(NSString *) DecToBinary: (int) decInt
{
int result = 0;
int multiplier;
int base = 2;
while(decInt > 0)
{
int r = decInt % 2;
decInt = decInt / base;
result = result + r * multiplier;
multiplier = multiplier * 10;
}
return [NSString stringWithFormat:@"%d",result];
我会使用位移来达到整数的每个位
x = x >> 1;
将位向左移动一位,小数13以位为单位表示为1101,因此将其向右移动会产生110 - > 6。
x&1
是掩码x与1
1101
& 0001
------
= 0001
组合这些行将从最低位到最高位迭代,我们可以将此位作为格式化整数添加到字符串中。
对于unsigned int,可能就是这样。
#import <Foundation/Foundation.h>
@interface BinaryFormatter : NSObject
+(NSString *) decToBinary: (NSUInteger) decInt;
@end
@implementation BinaryFormatter
+(NSString *)decToBinary:(NSUInteger)decInt
{
NSString *string = @"" ;
NSUInteger x = decInt;
while (x>0) {
string = [[NSString stringWithFormat: @"%lu", x&1] stringByAppendingString:string];
x = x >> 1;
}
return string;
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString *binaryRepresentation = [BinaryFormatter decToBinary:13];
NSLog(@"%@", binaryRepresentation);
}
return 0;
}
此代码将返回1101
,二进制表示为13。
使用do-while的缩写形式, x >>= 1
是x = x >> 1
的缩写形式:
+(NSString *)decToBinary:(NSUInteger)decInt
{
NSString *string = @"" ;
NSUInteger x = decInt ;
do {
string = [[NSString stringWithFormat: @"%lu", x&1] stringByAppendingString:string];
} while (x >>= 1);
return string;
}
NSMutableArray *arr = [[NSMutableArray alloc]init];
//i = input, here i =4
i=4;
//r = remainder
//q = quotient
//arr contains the binary of 4 in reverse order
while (i!=0)
{
r = i%2;
q = i/2;
[arr addObject:[NSNumber numberWithInt:r]];
i=q;
}
NSLog(@"%@",arr);
// arr count is obtained to made another array having same size
c = arr.count;
//dup contains the binary of 4
NSMutableArray *dup =[[NSMutableArray alloc]initWithCapacity:c];
for (c=c-1; c>=0; c--)
{
[dup addObject:[arr objectAtIndex:c]];
}
NSLog(@"%@",dup);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.