2014-02-07 26 views
0

以及找出如果在無符號短位被設置或沒有。所以如果返回1,則x中的位i將被設置,否則返回0。另外,我必須記住右邊的位是0,如b15b14b13 ... b3b2b1b0。那麼我試過這樣,但我認爲它沒有工作......任何幫助將不勝感激。找出是否在無符號短位被設置或不

short is_set(unsigned short x, int bit) { 
return (x >> bit) & 1; 

} 
+2

爲什麼你覺得你的解決方案是不正確的? – crockeea

+0

我可以檢查這個功能嗎?! @Eric – Manuel

+1

@Manuel你的回答是對的。 – BlackMamba

回答

1
short is_set(unsigned short x, int bit) { 

    return ((1 << bit) & x); 
} 

瓦爾特

+1

這個版本有什麼不同? – Gabe

+0

@Gabe So 5 + 3與6 + 2相同。 –

+0

............ @ valter – Manuel

0

嗯,你的解決方案似乎是正確的,但要回答爲什麼不工作,你應該張貼在那裏失敗的案例。

至此嘗試這種方法,並分享您的意見:

short is_set(unsigned short x, int bit) {  
    return (!!((1u << bit) & x)); 
} 
+0

這不符合OP的「返回1,如果第i位在x被設置,否則爲0」。 – chux

+0

@chux:更正了它! –

+0

什麼是!做? – Marichyasana

0

創建測試用例通過@Eric和@MadHatter的建議:

void Test(short x, int i, int expect) { 
    printf("Expect %d, is_set(%#x,%d) --> ", expect, x,i); 
    fflush(stdout); // Flush output as is_set() may fail. 
    int result = is_set(x,i); 
    printf(" %d, %s\n", result, expect == result ? "Success" : "Fail"); 
} 

void Tests(void) { 
    Test(0x0000, 0, 0); 
    Test(0x0001, 0, 1); 
    Test(0x1234, 2, 1); 
    Test(0x1234, 3, 0); 
    // etc. 
} 
Expect 0, is_set(0,0) --> 0, Success 
Expect 1, is_set(0x1,0) --> 1, Success 
Expect 1, is_set(0x1234,2) --> 1, Success 
Expect 0, is_set(0x1234,3) --> 0, Success 

函數正確執行「返回1 iff第x位置位,否則爲0「。

輔修:匹配代碼命名的要求。

// Return 1 iff bit i in x is set, 0 otherwise 
//         v 
short is_set(unsigned short x, int i) { 

次要:返回值爲1和0。這應該意味着int除非另有說明。

int is_set(unsigned short x, int i) { 
相關問題