【问题标题】:Decimal to Binary conversion method Objective-C十进制到二进制的转换方法Objective-C
【发布时间】:2014-04-17 10:50:19
【问题描述】:

您好,我正在尝试在 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];

【问题讨论】:

  • 相关:stackoverflow.com/questions/7911651/decimal-to-binary(您需要将生成的字符串转换为 NSString,但目标 c 是 c 的超集...
  • 这是一个相当奇怪的算法。如果要转换为字符二进制,为什么不直接转为字符呢? (至少让result 成为long,因为它往往是一个非常大的数字。)
  • (在 Java 中也有更直接的方法可以做到这一点。)
  • 顺便说一句,这不是一个“十进制到二进制”的转换器,它是一个数值到字符的二进制转换器。传入的值不表示为十进制,但实际上,在内部,(在所有现代机器中)是一个二进制数。

标签: ios objective-c algorithm binary decimal


【解决方案1】:

我会使用位移来达到整数的每一位

x = x >> 1;

将位向左移动一位,十进制 13 以位表示为 1101,因此将其向右移动创建 110 -> 6。

x&1

是用 1 掩码 x 的位

  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 &gt;&gt;= 1x = x &gt;&gt; 1 的缩写形式:

+(NSString *)decToBinary:(NSUInteger)decInt
{
    NSString *string = @"" ;
    NSUInteger x = decInt ;
    do {
        string = [[NSString stringWithFormat: @"%lu", x&1] stringByAppendingString:string];
    } while (x >>= 1);
    return string;
}

【讨论】:

  • 较长版本中变量 i 的原因是什么?似乎除了递增之外没有在循环中使用它?
【解决方案2】:
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);

【讨论】:

    猜你喜欢
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 2013-05-14
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    相关资源
    最近更新 更多