Dian007
Dian007

Reputation: 51

hex a to binary

i am trying to convert my hex value to binary value , but i am facing little problem . as i am new trying to learn my faults .

my code :

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

I'm getting

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

in my code 0 values are eliminated . i want 8bits like(00000001,00001100.....) can any one tell me the reason

Upvotes: 0

Views: 324

Answers (1)

user529758
user529758

Reputation:

When the most significant bit is reached, your algorithm stops the conversion. Why not force the loop to always execute 8 times?

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

By the way, here's a cleaner/shorter/simpler approach that doesn't involve highly superfluous copying and uses characters instead of string objects for hyper efficiency (just kidding, I'm all against micro-optimizations, but I feel like inserting an NSString before another one is unnecessary, especially if the number of bits is known and constant). This also assumes UTF-8 and exploits the fact that hexadecimal and binary representation have a very nice relationship, 16 being the 4th power of 2:

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

Upvotes: 2

Related Questions