0

我正在尝试将我的十六进制值转换为二进制值,但我面临的问题很小。因为我是新手,试图学习我的错误。

我的代码:

NSMutableString *str;
NSString *dd = @"192:168:1:2:0B:2:D:00";    
NSCharacterSet *donotwant1 = [NSCharacterSet characterSetWithCharactersInString:@":""];
dd =[[dd componentsSeparatedByCharactersInSet:donotwant1] componentsJoinedByString:@" "];
NSMutableArray *array = [[dd componentsSeparatedByString:@" "] mutableCopy];

[array removeObjectAtIndex:0];
//NSLog(@"%@",array);

for (int j=0; j<[array count]; j++) {
    NSScanner *scan = [NSScanner scannerWithString:[array objectAtIndex:j]];
    unsigned int i=0;

    if ([scan scanHexInt:&i]) {
        // NSLog(@"numbner is %ustr", i);
    }

    NSInteger theNumber = i;
    str = [NSMutableString string];
    for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1) {
        // Prepend "0" or "1", depending on the bit
        [str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];

        [array removeObjectAtIndex:j];
        [array  insertObject:str atIndex:j];
    }
}

NSLog(@"Binary version: %@", array);

我越来越

1,1100,11001111,1111,1111,11101111......

在我的代码中 0 值被消除。我想要 8bits like(00000001,00001100 .....) 谁能告诉我原因

4

1 回答 1

2

当达到最高有效位时,您的算法会停止转换。为什么不强制循环总是执行 8 次?

for (int numberCopy = theNumber, int i = 0; i < 8; numberCopy >>= 1, i++) {
    // loop body here
}

顺便说一句,这是一种更简洁/更短/更简单的方法,它不涉及高度多余的复制,并且使用字符而不是字符串对象来实现超高效率(开玩笑,我完全反对微优化,但我觉得插入一个NSStringbefore另一个是不必要的,尤其是在位数已知且恒定的情况下)。这也假设 UTF-8并利用十六进制和二进制表示具有非常好的关系这一事实,16 是 2 的 4 次方:

NSString *dd = @"01:0C:CF:0F:EF:AF:BD:00";

NSArray *bytes = [dd componentsSeparatedByString:@":"];

NSMutableArray *binaries = [NSMutableArray array];

NSString *lookup[256];
lookup['0'] = @"0000";
lookup['1'] = @"0001";
lookup['2'] = @"0010";
lookup['3'] = @"0011";
lookup['4'] = @"0100";
lookup['5'] = @"0101";
lookup['6'] = @"0110";
lookup['7'] = @"0111";
lookup['8'] = @"1000";
lookup['9'] = @"1001";
lookup['A'] = @"1010";
lookup['B'] = @"1011";
lookup['C'] = @"1100";
lookup['D'] = @"1101";
lookup['E'] = @"1110";
lookup['F'] = @"1111";


for (NSString *s in bytes) {
    unichar n1 = [s characterAtIndex:0];
    unichar n0 = [s characterAtIndex:1];
    [binaries addObject:[lookup[n1] stringByAppendingString:lookup[n0]]];
}

NSLog(@"%@", binaries);
于 2013-03-06T20:26:03.713 回答