Convert hex byte(no displayable characters) into 8 bit binary with leading zero

482 views Asked by At

The idea is I am getting byte like 0x80,0x65, and I will need to convert these bytes into binary with 8 bit binary with leading zero if it's less than 8 bits. (80 -> 1000 0000, 65-> 0110 0101).

I have found this:[How to Convert NSInteger or NSString to a binary (string) value, but it doesnt seems it use leading zero.

Could anyone show me how to add leading 0's if they converted binary is less than 8 bits without using any additional framework?

Update:

I have found a way to do this, however it doesn't seems efficient. By checking the length of the string, if it's less than 8, I just add missing 0 into it. Below is example of length 6, so to cover all cases I will need 8 cases. Any one have better way of doing this?

if ([str length]==6) { str=[NSMutableString stringWithFormat:@"%@%@",@"00",str]; NSLog(@"Binary version: %@", str); }

1

There are 1 answers

0
Rabbit On

Found the answer:

NSInteger theNumber = mynumber;
NSMutableString *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];
}
for(int i= [str length];i < 8;i++){
    str=[NSMutableString stringWithFormat:@"%@%@",@"0",str];
}