Search code examples
objective-chexbytensdatabit

How to get the Bit value by index from NSData Hex value in Objective C


I have a NSData of Hex

<80140142 0073ffff ffff04ff>

I can get the Byte value by index

NSData *commandIDData = [mqttResponseData subdataWithRange:NSMakeRange(3,1)]; <42> // 66

How Can I get the Bit value by index?

0100 0010

e.g

index[0]=0 index[1]=1
index[2]=0
index[4]=0


Solution

  • NSData *statusData = [mqttResponseData subdataWithRange:NSMakeRange(3,1)];
    
    const unsigned char *statusByte = [statusData bytes];//Hex<4F>/Decimal-79/Binary-01001111
    
    for (int i = 0 ; i < 8; i++) {
        bool chanelValue = [[NSNumber numberWithChar:(*statusByte >> i) & 0x01] boolValue];//i = 0 right most bit
        NSLog(@"chanelValue %d: %d",i+1,chanelValue);//1 1 1 1 0 0 1 0
    }