以二进制格式打印的 NSString [英] NSString to Print in in binary format

查看:147
本文介绍了以二进制格式打印的 NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白下面将 int 转换为 byte 的情况,下面的 java 代码可以打印字节值如下

I dont understand of the below case of converting int to byte , the below java code can able to print the byte value as below

System.out.println("二进制输出:::"+Byte.toString(bo[0]));
System.out.println("二进制输出::: "+Byte.valueOf(bo[1]));
System.out.println("二进制输出::: "+Byte.valueOf(bo[2]));
System.out.println("二进制输出::: "+Byte.valueOf(bo[3]));
System.out.println("二进制输出:::"+new String(bo));

System.out.println("binary output ::: "+Byte.toString(bo[0]));
System.out.println("binary output ::: "+Byte.valueOf(bo[1]));
System.out.println("binary output ::: "+Byte.valueOf(bo[2]));
System.out.println("binary output ::: "+Byte.valueOf(bo[3]));
System.out.println("binary output ::: "+new String(bo));

二进制输出 ::: 0
二进制输出 ::: 0
二进制输出 ::: 0
二进制输出 ::: 1
二进制输出 ::: squaresquaresquaresquare ( 4 square chars) - 二进制数据

binary output ::: 0
binary output ::: 0
binary output ::: 0
binary output ::: 1
binary output ::: squaresquaresquaresquare ( 4 square chars) - binary data

但是当我将相同数据的objective-c代码制作成最终的NSString时,它也会打印为0001"但不是二进制格式(4个正方形字符)

but when i make a objective-c code to the same data into final NSString it also prints as "0001" but not in binary format ( 4 square chars)

我需要二进制格式的 NSString 如何以二进制格式打印 NSString 而不是0001"

I need NSString in binary format how do i print NSString in binary format instead of "0001"

请帮忙

推荐答案

如果可读性是一个问题,让我建议一个快速例程,它将把一个 int 转换成一串由1"和0"组成的半字节大小的分组字符:

If readability is an issue, let me suggest a quick routine which will turn an int into a string of nibble-sized groupings of "1" and "0" characters:

NSString *binaryRepresentation(int value)
{
    long nibbleCount = sizeof(value) * 2;
    NSMutableString *bitString = [NSMutableString stringWithCapacity:nibbleCount * 5];

    for (int index = 4 * nibbleCount - 1; index >= 0; index--)
    {
        [bitString appendFormat:@"%i", value & (1 << index) ? 1 : 0];
        if (index % 4 == 0)
        {
            [bitString appendString:@" "];
        }
    }

    return bitString;
}

这样
binaryRepresentation(1) 返回 0000 0000 0000 0000 0000 0000 0000 0001

binaryRepresentation(1423) 返回 0000 0000 0000 0000 0000 0101 1000 1111

这篇关于以二进制格式打印的 NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆