如何将 NSInteger 转换为二进制(字符串)值 [英] How to Convert NSInteger to a binary (string) value
本文介绍了如何将 NSInteger 转换为二进制(字符串)值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图弄清楚如何将一个 NSInteger(比如 56)转换为一个 NSString,它是原始 (int) 值的二进制表示.也许有人知道一种可以接受 56 并在 Objective C 中返回111000"的格式化技术.谢谢大家.
I am trying to figure out how to convert an NSInteger, say 56, to an NSString that is a binary representation of the original (int) value. Perhaps someone knows a formatting technique that can accept 56 and return "111000" within Objective C. Thanks All.
推荐答案
没有内置的格式化操作符可以做到这一点.如果您想将其转换为十六进制字符串,您可以这样做:
There's no built-in formatting operator to do that. If you wanted to convert it to a hexadecimal string, you could do:
NSString *str = [NSString stringWithFormat:@"%x", theNumber];
要将其转换为二进制字符串,您必须自己构建它:
To convert it to a binary string, you'll have to build it yourself:
NSMutableString *str = [NSMutableString stringWithFormat:@""];
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1)
{
// Prepend "0" or "1", depending on the bit
[str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
}
这篇关于如何将 NSInteger 转换为二进制(字符串)值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文