2012-09-13 59 views
-3

一個替代函數編寫將返回在其中xi個字節已經取代b值的函數:如何編寫C

unsigned replace_f (unsigned x, int i, unsigned char b){ 

} 

EX:replace_f(0x12345678, 2, 0xBC) --> 0x12BC5678

+3

你能告訴我們你到目前爲止嘗試過嗎?也許我們可以指出它的錯誤。 – Mysticial

+0

嗯,我是C新手,所以我不知道從哪裏開始。 – sebi

+1

@sebi:雖然我們總是樂意幫助您解決具體問題,但我們大多數人沒有時間教您一門語言 - 這基本上就是您所要求的。請花一些時間先了解C,然後隨時回來,找出我們可以幫助您的具體問題。 – Mac

回答

1
unsigned replace_f (unsigned x, int i, unsigned char b){ 
    unsigned char *place = (unsigned char*)&x; 
    place[sizeof(int)-i] = b; 
    return x; 
} 

ASSU我小endian

+3

你應該注意,你假設小端 – wich

1

沒有嘗試一下,不過這可能是工作:

unsigned replace_f (unsigned x, int i, unsigned char b){ 
    char *c; 

    c = (char *)&x; 
    c[i] = b; 
    return x; 
} 
+2

你應該注意,你認爲大endian – wich

+0

yee ..我應該,但我也認爲x86:D – Pyjong

+0

不,你不知道。 x86是小端,這不是你的代碼支持 – wich