微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VB6:当然这个简单的Hex加法错了吗?

我在一些VB6代码中得到奇怪的结果,我已经缩小到这个:

Debug.Print Hex(&hEDB80000 + &h8300)

显示EDB78300

这不可能是正确的吗?当然应该是EDB88300?

我疯了吗?

解决方法

不要忘记 negative numbers are expressed in binary,VB6和VB.NET如何解释和& h8300这样的数字不同.

因为& hEDB80000不适合16位,VB将其解释为长(32位).因为高位被设置,VB6知道它是负的.

让我们撤消two’s complement(在32位世界中)来计算小数值

(~&hEDB80000 + 1) = &h1247FFFF + 1 = &h12480000 = 306708480

因为符号位已设置,那是-306708480

因为& h8300适合16位,VB将其解释为整数(16位).因为高位被设置,VB6知道它是负的.

让我们撤消两个补码(在一个16位的世界中)

(~&h8300 + 1) = &h7DFF + 1 = &h7D00 = 32000

由于符号位已设置,因此为-32000.当添加发生时,两个值都被认为是长(32位).

(-306708480) + (-32000) = -306740480

让我们把它放回两个补码十六进制中

~(306740480 - 1) = ~(&h12487D00 - 1) = ~(&h12487CFF) = &hEDB78300

所以& hEDB78300是正确的答案.

笔记:

我个人认为混乱发生的原因如下:

&h0004000 is interpreted as  16384 // Fits in 16-bits,sign bit is not set
&h0008000 is interpreted as -32768 // Fits in 16-bits,sign bit is set
&h0010000 is interpreted as  65536 // Requires 32-bits,sign bit is not set

正如在另一篇文章中提到的,你可以通过明确地将值标记为long来解决这个问题

&h0004000& is interpreted as  16384 
&h0008000& is interpreted as  32768 
&h0010000& is interpreted as  65536

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐