将NSString转换为位值

时间:2013-09-30 06:47:17

标签: objective-c nsstring

NSString *strVal= @"BAAA";

如何将上述字符串转换为位值?我应该在此之前进行字节转换吗? 需要帮助。我之前检查过this question进行整数转换。

1 个答案:

答案 0 :(得分:1)

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

我希望你想要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