C語(yǔ)言中數(shù)據(jù)的左移右移應(yīng)用
unsigned long Peek(long address )
{
unsigned long value;
//if( address != PokePointer )
{SetAddress( address );}
//if( PeekPointer >= PeekLimit )
//{throw "Peek addressing error!";}
value += Read_Register( DATA_A ) << 24;
value += Read_Register( DATA_B ) << 16;
value += Read_Register( DATA_C ) << 8;
value +=Read_Register( DATA_D );
//PeekPointer++; /* maintain local pointer */
return value;
}
Read_Register( DATA_A ) 返回的數(shù)據(jù)都是字節(jié)型的,不知有沒(méi)有人能預(yù)言出PPEK()函數(shù)的運(yùn)行結(jié)果,顯然這個(gè)函數(shù)內(nèi)部存在著一個(gè)低級(jí)的錯(cuò)誤,因?yàn)樽止?jié)型的數(shù)據(jù)左移8位所有位將都會(huì)變成0!因而PPEK函數(shù)返回的只有Read_Register( DATA_D );那么正確的應(yīng)該是什么樣呢?我的改正如下:
value += Read_Register( DATA_A );
value =(value<<8) + Read_Register( DATA_B );
value =(value<<8) + Read_Register( DATA_C );
value =(value<<8) + Read_Register( DATA_D );
或者:
value +=(unsigned long)Read_Register( DATA_A ) << 24;
value +=(unsigned long)Read_Register( DATA_B ) << 16;
value +=(unsigned long)Read_Register( DATA_C ) << 8;
value +=(unsigned long)Read_Register( DATA_D );
從以上本人所犯的低級(jí)錯(cuò)誤,我得出一個(gè)結(jié)論就是在寫(xiě)代碼的時(shí)候左移右移一定要注意被移數(shù)據(jù)的類(lèi)型也就是他的位數(shù),是否在操作中會(huì)導(dǎo)致數(shù)據(jù)溢出!
再補(bǔ)充一下:左移<<、右移>>的優(yōu)先級(jí)相對(duì)于數(shù)學(xué)運(yùn)算是比較低的,大家看一下下面的表達(dá)式:
c=a<<8+b;//那么這句的意思就是將a左移8+b位然后賦給c
那么你要實(shí)現(xiàn)將a左移8位然后加上b的值賦給c的話就應(yīng)該寫(xiě)成如下表達(dá)式:
c=(a<<8)+b;
以上都是本人犯過(guò)的低級(jí)錯(cuò)誤,希望看到的能引以為戒!??!
評(píng)論