您的位置:首页 > 其它

将整数转为二进制

2016-03-03 10:02 211 查看
将 int 类型的数转为二进制形式的字符串,sizeof()括号内可写int、short、char、long (其他没试过)

- (NSString *)intToBinary:(int)intValue{
int byteBlock = 8,    // 每个字节8位
totalBits = sizeof(int) * byteBlock, // 总位数(不写死,可以适应变化)
binaryDigit = 1;  // 当前掩(masked)位
NSMutableString *binaryStr = [[NSMutableString alloc] init];   // 二进制字串
do
{
// 检出下一位,然后向左移位,附加 0 或 1
[binaryStr insertString:((intValue & binaryDigit) ? @"1" : @"0" ) atIndex:0];
// 若还有待处理的位(目的是为避免在最后加上分界符),且正处于字节边界,则加入分界符|
if (--totalBits && !(totalBits % byteBlock))
[binaryStr insertString:@"|" atIndex:0];
// 移到下一位
binaryDigit <<= 1;
} while (totalBits);
// 返回二进制字串
return binaryStr;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: