Show NSData as binary in a NSString

前端 未结 1 1407
执念已碎
执念已碎 2021-01-06 01:59

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\'

1条回答
  •  礼貌的吻别
    2021-01-06 02:37

    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);
    

    The workaround function:

    - (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!
    }
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题