将整数转为二进制

来源:互联网 发布:sougou输入法windows版 编辑:程序博客网 时间:2024/05/01 08:46

将 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;}



0 0