十进制到二进制转换方法Objective-C

the*_*y05 2 algorithm binary decimal objective-c ios

您好我正在尝试在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];
Run Code Online (Sandbox Code Playgroud)

Vik*_*ica 10

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

x = x >> 1;
Run Code Online (Sandbox Code Playgroud)

将位向左移动一位,小数13以位为单位表示为1101,因此将其向右移动会产生110 - > 6.

x&1
Run Code Online (Sandbox Code Playgroud)

是掩码x与1

  1101
& 0001
------
= 0001
Run Code Online (Sandbox Code Playgroud)

组合这些行将从最低位到最高位迭代,我们可以将此位作为格式化整数添加到字符串中.

对于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;
}
Run Code Online (Sandbox Code Playgroud)

这段代码将返回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;
}
Run Code Online (Sandbox Code Playgroud)