2014-11-21 42 views
0

我該如何檢查一個NSData對象中的位0-6是否爲0x0001等於1?檢查一個NSData對象中的位

我的代碼

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上這是一個小端系統

+0

評論不適用於擴展討論;這個對話已經[轉移到聊天](http://chat.stackoverflow.com/rooms/65324/discussion-on-question-by-stackoverflew-checking-bits-in-an-nsdata-object)。 – Taryn 2014-11-21 02:26:22

+0

'if(theByte&0x01)' – 2014-11-21 02:28:10

+0

我明白,對於一個字節,購買一個字節的8個單獨位中的每一個是什麼? – stackOverFlew 2014-11-21 02:36:10

回答

1

這是我結束了學習

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。

+1

'5'不是一個有效的二進制數字。你的意思是'0b00010000'。 – rmaddy 2014-11-21 04:04:34

+0

哈哈真正不知道我沒有看到 – stackOverFlew 2014-11-21 08:14:11