https://en.wikipedia.org/wiki/Arithmetic_shift (算數移位)
這又是以前學生時代有學過的觀念,但後來又還回去的東西...
溫習一下....因為這在arm指令模擬中不少地方都得用到.
簡單來說邏輯移位不管左右移,一律都是把多出來的位數塞零.
而算術運算左移跟邏輯移位一樣塞零,右移需要考慮到singed的屬性,假若最高位是1,則填補1,最高位是0,則填補0.
簡單扼要....
要注意的是,要確定好自己語言的位移運算到底是怎麼運作,否則結果可能跟所想不同.
c# wiki中有提到 :
Some languages, such as the .NET Framework and LLVM, also leave shifting by the bit width and above "unspecified" (.NET) or "undefined" (LLVM). Others choose to specify the behavior of their most common target platforms, such as C Sharp (programming language) which specifies the x86 behavior.
目前在微軟x86平台上不管是邏輯還是算數移位, 一律都是以 << 和 >> 來當 左右移位運算符號,邏輯跟算數的差異在於被平移的數字以 singed 還是 unsigned 來表示 , 如果被平移的數是unsigned的,則會進行邏輯平移,如果被平移的數是signed則會進行算數平移.
ex.
int a = 1234;
int b = 6;
int r = a >> b ; (邏輯平移運算)
===
uint a = 1234 ;
int b = 6 ;
uint r = a >> 6 ; (算數平移運算)
應該多數狀況是通用,但不保證其他少數個別平台或是個別實作也是一樣的狀況.
沒有留言:
張貼留言