1
NSString *strVal= @"BAAA";

如何将上述字符串转换为位值?我应该在此之前进行字节转换吗?在这方面需要帮助。我以前检查过这个问题的整数转换。

4

1 回答 1

1

是否先将字符串转换为 UTF-8 取决于您;这取决于你想要什么。使用该类型在内部NSString将字符存储为 UTF-16(实际上可能是 UCS-2)unichar,因此您需要决定是需要内部表示的二进制文件还是其他一些外部编码的二进制文件。

我希望你想要 UTF-8 编码的二进制文件,所以试试这个(经过测试):

#import <Foundation/Foundation.h>

@interface BinFuncs : NSObject
+ (NSString *)binaryOfString:(NSString *)str;
@end

@implementation BinFuncs

+ (NSString *)binaryOfString:(NSString *)str {
    NSMutableString *binStr = [[NSMutableString alloc] init];
    const char *cstr = [str UTF8String];
    size_t len = strlen(cstr);
    for (size_t i = 0; i < len; i++) {
        uint8_t c = cstr[i];
        for (int j = 0; j < 8; j++) {
            [binStr appendString:((c & 0x80) ? @"1" : @"0")];
            c <<= 1;
        }
    }
    return binStr;
}

@end

int main(int argc, const char **argv) {
    @autoreleasepool {
        for (int i = 1; i < argc; i++) {
            NSString *binStr = [BinFuncs binaryOfString:[NSString stringWithUTF8String:argv[i]]];
            NSLog(@"%@", binStr);
        }
    }

    return 0;
}

$ clang -o binstr binstr.m -framework Foundation
$ ./binstr 'the quick brown fox jumps over the lazy dog'
2013-09-30 09:19:49.674 binstr[58474:707] 01110100011010000110010100100000011100010111010101101001011000110110101100100000011000100111001001101111011101110110111000100000011001100110111101111000001000000110101001110101011011010111000001110011001000000110111101110110011001010111001000100000011101000110100001100101001000000110110001100001011110100111100100100000011001000110111101100111
于 2013-09-30T08:00:48.233 回答