在NSString中以二进制形式显示NSData

6
我有一个二进制文件(file.bin)在资源文件夹中,我想读取它并以二进制形式显示。首先,我尝试将其显示在UILabel中,但是我的想法是将二进制信息放入数组中。代码如下:

` NSData *databuffer; NSString *stringdata;

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"bin"];  
NSData *myData = [NSData dataWithContentsOfFile:filePath];

if (myData) {  
        stringdata = [NSString stringWithFormat:@"%@",[myData description]]; 
        labelfile.text = stringdata;
}  

但它以十六进制显示数据。我该如何将其转换为二进制并放入NSMutableArray中?谢谢。


1
“在二进制中”这个词组,您是指“以2为底的表示法”吗? - Sergey Kalinichenko
是的,就像这样:NSSTRING string = @"01000101000.." - Sergiodiaz53
很确定你需要编写自己的二进制解码器。我曾经写过一种语言,可以将B"101010.."解释为二进制文字,但我从未见过任何标准语言可以读取或格式化二进制。 - Hot Licks
1个回答

8
我不知道是否有本地工具可以做到这一点,但我可以提出一个解决方案。为什么不自己编写一个函数来进行转换呢?以下是我的示例:
在获取十六进制值的位置:
NSString *str = @"Af01";
NSMutableString *binStr = [[NSMutableString alloc] init];

for(NSUInteger i=0; i<[str length]; i++)
{
    [binStr appendString:[self hexToBinary:[str characterAtIndex:i]]];
}
NSLog(@"Bin: %@", binStr);

绕过功能:
- (NSString *) hexToBinary:(unichar)myChar
{
    switch(myChar)
    {
        case '0': return @"0000";
        case '1': return @"0001";
        case '2': return @"0010";
        case '3': return @"0011";
        case '4': return @"0100";
        case '5': return @"0101";
        case '6': return @"0110";
        case '7': return @"0111";
        case '8': return @"1000";
        case '9': return @"1001";
        case 'a':
        case 'A': return @"1010";
        case 'b':
        case 'B': return @"1011";
        case 'c':
        case 'C': return @"1100";
        case 'd':
        case 'D': return @"1101";
        case 'e':
        case 'E': return @"1110";
        case 'f':
        case 'F': return @"1111";
    }
    return @"-1"; //means something went wrong, shouldn't reach here!
}

希望这可以帮到你!

成功了!!!非常感谢!!!看起来有点奇怪,因为我的文件是二进制的,我需要转换一下,但没关系。 - Sergiodiaz53
很高兴为您服务 :) 请记得接受此答案,如果它解决了您的问题,这样它就会显示为正确答案。 - antf
G到Z呢? - Supertecnoboff
@Supertecnoboff 请再次阅读问题,数据是十六进制而不是英文字母,因此在十六进制中没有G到Z。这个答案将十六进制值转换为二进制。如果您想要英文字母,则必须使用ASCII表获取每个字符的整数值,然后将该整数转换为二进制。 - antf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接