我正在學習C,我仍然是一個非常初學者。複製n位給定的位置從x到y在C
我的問題是以下。我有一個unisgned int x和一個unsigned int y。我想從x的位置p複製n位到y的相同位置。我發現了一些類似的問題,但不是在C中,大多數情況下,如果採用最右邊或最左邊的位,問題稍有不同。我還想找到一個不依賴於機器上整數表示的解決方案。
這裏是我做過什麼
unsigned fix_bits(unsigned x, unsigned y, int n, int p)
{
unsigned u1,u2,u3,u4,x1,y1,yf;
u1 = ~0; /*vector of 1*/
u2 = (u1>>n); /*0 from 0 to n-1 and 1s*/
u3 = ~(u2);/*1 from 0 to n-1 and 0s*/
u4 = u3>>p;/*0 from 0 to p-1, n 1 from p to p+n+1 and 0s*/
x1 = (x & u4);/*only keep n bits of x from position p*/
y1 = (y | u4);/*set y bit from p to (p+n+1) to 1, rest remains unchanged (0 | bit = bit)*/
yf = (x1 | y1);
return yf;
}
但它不工作:
放置2位在28〜32 3位的結果是402653216
是否有人知道我是什麼我做錯了?
非常感謝您
首先,從位置最顯著位計數。這完全有可能,但不尋常。其次,你的多路複用器壞了。嘗試'y1 = y&〜u4' – harold
在28到32的位置3放置2位的預期結果是什麼? – anatolyg
我假定從二進制查看結果(請參見下圖),您只需要從LSB而不是MSB進行操作。這是一個正確的假設嗎? (即位置5從左邊開始5位,從右側開始5位) – ryyker