hex a到binary

时间:2013-03-06 20:21:48

标签: iphone objective-c xcode ipad hex

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

我的代码:

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值被删除。我想8位像(00000001,00001100 .....)可以任何人告诉我原因

1 个答案:

答案 0 :(得分:2)

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

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

顺便说一句,这是一个更简洁/更简单/更简单的方法,不涉及高度多余的复制,并使用字符而不是字符串对象来提高效率(只是开玩笑,我反对微优化,但我觉得不需要在另一个之前插入NSString,特别是如果位数已知并且不变)。这也假定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);