shr 位的右移指令的困惑(100)

M

mayong

Unregistered / Unconfirmed
GUEST, unregistred user!
给学生讲课时发现:delphi6.0var i:=-20;i:=i shr 1;label1.caption:=inttostr(i)
//结果是正数label1.caption:=inttostr(-20 shr 1)
//结果是负数 -10=============================================delphi10中:var i:=-20;i:=i shr 1;label1.caption:=inttostr(i)
//结果是正数label1.caption:=inttostr(-20 shr 1)
//结果是正数=========================能否有人给出解释?万分感谢!!!!!
 
很奇怪,呵呵,delphi7的shr帮助:The operations x shl y and x shr y shift the value of x to the left or right by y bits,which(if x is an unsigned integer) is equivalent to multiplying or dividing x by 2^y;the result is of the same type as x.For example, if N stores the value 01101(decimal 13),then N shl 1 returns 11010(decimal 26).Note that the value of y is interpreted modulo the size of the type of x.Thus for example, if x is an integer, x shl 40 is interpreted as x shl 8 because an integer is 32 bits and 40 mod 32 is 8.--------------这里面特意说明了(if x is an unsigned integer)才成立它下面的说法,于是我做了以下测试:caption := IntToStr( Integer (-20) shr 1)
//结果是 -10 ;Integer -2147483648..2147483647 signed 32-bitcaption := IntToStr( Longint (-20) shr 1)
//结果是 -10 ;Longint -2147483648..2147483647 signed 32-bitcaption := IntToStr( Cardinal (-20) shr 1)
//结果是2147483638 ;Cardinal 0..4294967295 unsigned 32-bitcaption := IntToStr( Longword (-20) shr 1)
//结果是2147483638 ;Longword 0..4294967295 unsigned 32-bit---我没D10环境,无法测试了,做了这些基础工作,等待别人来解释了,呵呵
 
caption := IntToStr( Cardinal (-20) shr 1)
//结果是2147483638 ;Cardinal 0..4294967295 unsigned 32-bitcaption := IntToStr( Longword (-20) shr 1)
//结果是2147483638 ;Longword 0..4294967295 unsigned 32-bit================这个结果是显然的,Longword (-20)已经把负数强制转换为正数,所以...
 
其他语言(C++,C#),负数右移,最高位补1delphi,负数右移,最高位补0,但表达式  -20 shr 1=负数  说明是:最高位补1
 
搞不清编译器怎么搞的情况下,就先转成正数,再右移,完了转回来。不应当受编译器左右,不然在不同的版本下可能会出现差错。这样的依赖编译器的不明确代码没有可移植性,转到FREEPASCAL可能又是另一结果。而且讲课中这个例子在实际应用中好像我从来没有遇到过,学生初学时研究这些细节没有什么意义,这是我们应试教育的一大特色。
 
汇编中 逻辑右移 算术右移 的差别 delphi没体现出来
 
通过Shift+F8跟踪发现 i:=i shr 1;调用了汇编函数shr而 J:= (-20) Shr 1;则是简单的赋值,说明是编译期间,Delphi就已经把结果计算好了的。你在delphi10中也通过这种方式跟踪一下吧。
 

Similar threads

S
回复
0
查看
745
SUNSTONE的Delphi笔记
S
S
回复
0
查看
692
SUNSTONE的Delphi笔记
S
S
回复
0
查看
1K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
928
SUNSTONE的Delphi笔记
S
S
回复
0
查看
950
SUNSTONE的Delphi笔记
S
顶部