本文介绍了如何转换NSInteger的或者NSString的二进制(字符串)值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人有在Objective-C的一些code到NSInteger的或的NSString转换为二进制字符串?

Anybody has some code in objective-c to convert a NSInteger or NSString to binary string?

例如:

56 - > 111000

56 -> 111000

有计算器中的一些code试图做到这一点,但它doesn't的工作。

There are some code in stackoverflow that try do this, but it doesn´t work.

感谢

推荐答案

不知道这对SO例子没有为你工作,但Adam在这里罗森菲尔德的回答似乎工作。我已经更新它删除编译器警告:

Not sure which examples on SO didn't work for you, but Adam Rosenfield's answer here seems to work. I've updated it to remove a compiler warning:

// Original author Adam Rosenfield... SO Question 655792
NSInteger theNumber = 56;
NSMutableString *str = [NSMutableString string];
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1)
{
    // Prepend "0" or "1", depending on the bit
    [str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
}

NSLog(@"Binary version: %@", str);

这篇关于如何转换NSInteger的或者NSString的二进制(字符串)值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 23:38