从NSData字节中提取位

时间:2015-07-29 08:09:07

标签: ios nsdata

我想从NSData字节中提取以下位中的所有位:

status data byte:< 0011 ...

结果全部为0000 0000 0000 0000。你能告诉我怎么样吗?

B

...

                NSData *aData = [valueData subdataWithRange:NSMakeRange(0, 2)]; //16 bit status

                status= [self bitsToInt:aData];

                NSString *aString = [NSString stringWithFormat:@"%d", status];     

 int value = [aString intValue];
                NSlog(@"sadasd value : ,%d" ,value );

                unsigned thbit0 = (1 << 0) & value;
                unsigned thbit1 = (1 << 1) & value;
                unsigned thbit2 = (1 << 2) & value;
                unsigned thbit3 = (1 << 3) & value;
                unsigned thbit4 = (1 << 4) & value;
                unsigned thbit5 = (1 << 5) & value;
                unsigned thbit6 = (1 << 6) & value;
                unsigned thbit7 = (1 << 7) & value;
                unsigned thbit8 = (1 << 8) & value;
                unsigned thbit9 = (1 << 9) & value;
                unsigned thbit10 = (1 << 10) & value;
                unsigned thbit11= (1 << 11) & value;
                unsigned thbit12 = (1 << 12) & value;

1 个答案:

答案 0 :(得分:-1)

您可以尝试使用位字符串而不是整数值来进行额外的位提取。

这是简单的解码器:

- (NSString *)getBitsFromData:(NSData *)data
{
    NSMutableString *result = [NSMutableString string];
    const uint8_t *bytes = [data bytes];
    for (NSUInteger i = 0; i < data.length; i++)
    {
        uint8_t byte = bytes[i];
        for (int j = 0; j < 8; j++)
        {
            ((byte >> j) & 1) == 0 ? [result appendString:@"0"] : [result appendString:@"1"];
        }
    }
    return result;
}

测试:

NSString *test = @"test";
NSLog(@"%@", [self getBitsFromData:[test dataUsingEncoding:NSUTF8StringEncoding]]);

结果:

2015-07-29 11:37:31.768 Test[18342:9947704] 00101110101001101100111000101110