检查NSData对象中的位

时间:2014-11-21 01:35:07

标签: objective-c c byte bits

如何检查NS 0x0001的NSData对象中的0-6位是否等于1?

我的代码

const char *byte = [dataObject bytes];
for (int i=0; i<2; i++) {
    char n = byte[i];
    char buffer[9];
    buffer[8] = 0; //for null
    int j = 8;
    while(j > 0)
    {
        if(n & 0x01)
        {
            buffer[--j] = '1';

            //a bit is equal to 1 from my understanding
        } else
        {
            buffer[--j] = '0';
        }

        n >>= 1;
    }
}

说第1位是1,显然不是真的。

这可以在iPhone上运行,这是一个小小的Endian系统

1 个答案:

答案 0 :(得分:2)

这就是我最终学习的内容

const char *byte = [fixtureStatusBasic bytes]; //objective c, puts the 2 bytes into *byte
char n = byte[0]; //first byte is now called n
if(n & 0b00111111){ //AND the byte "n" with 6 least significant bits set to 1 to see if any of the 6 bits is set to 1

    //if this is true, and the program goes here, that means that one of the bits is set to 1

}

要查看是否设置了第5位,

if(n & 0b00010000){

    //5th least significant byte is set to 1. 
}
谢谢freenode。