显示的NSData如在的NSString二进制 [英] Show NSData as binary in a NSString
问题描述
我在资源文件夹中的二进制文件(file.bin),我想读它,并显示它作为二进制。这个想法它把二进制信息到一个数组,但是,起初,我试图证明它在一个UILabel,像:
I have a binary file (file.bin) in the resources folder, I want to read it and show it as binary. The idea its to put the binary information into a array, but, at first, I'm trying to show it in a UILabel, like that:
`NSData的*的DataBuffer;
* NSString的StringData是;
` 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里?
谢谢你。
But it shows the data in HEX. How can I do it in binary to put it in a NSMutableArray? Thanks.
推荐答案
我不知道是否有任何原生,做了,但我可以提出一个解决方法的解决方案。你为什么不去做自己的函数执行转换。这是我的例子:
I don't know if there is anything native that does that but I can propose a workaround solution. Why don't you do your own function that does the conversion. Here is my example:
在这个地方你得到的十六进制值:
In the place you get the Hex values:
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!
}
希望这有助于!
这篇关于显示的NSData如在的NSString二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!