VB6: Is this a simple addition to Hex wrong?

I get odd results in some VB6 code that I narrowed down to this:

Debug.Print Hex(&hEDB80000 + &h8300) 

Shows EDB78300

This is not right, is it? Surely it should be EDB88300 ?

I've gone crazy?

+4
source share
2 answers

Remember that negative numbers are expressed in binary , and VB6 and VB.NET interpret numbers like & h8300 differently.

Since & hEDB80000 does not match 16 bits, VB interprets it as long (32-bit). Since the high bit is set, VB6 knows that it is negative.

Cancel two additions (in a 32-bit world) to determine the decimal value

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

since the sign bit has been set, that is -306708480

Since & h8300 fits in 16 bits, VB interprets it as an integer (16 bits). Since the high bit is set, VB6 knows that it is negative.

Cancel two add-ons (in a 16-bit world)

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

since the sign bit has been set, -32000 . When adding occurs, both values ​​are considered long (32 bits).

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

Put this on two hex additions

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

So & hEDB78300 is the correct answer.


Notes:

I personally think the confusion is due to the following:

 &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 

as mentioned in another post, you can get around this by explicitly specifying the values ​​as longs

 &h0004000& is interpreted as 16384 &h0008000& is interpreted as 32768 &h0010000& is interpreted as 65536 
+15
source

Potentially, because VB6 sees & h8300 as an integer with a value of -32000. To get the results you expected, you would need to label this as Long: -

 Debug.Print Hex(&hEDB80000 + &h8300&) 

What you did was add Long to Interger. To do this, VB6 first extends Integer to Long, since & h8300 is a negative number, which Long, which it converts, ends with the value & hFFFF8300. Armed with this value, you can see that the result returned by VB6 is correct.

 FF + B8 = B7 with carry bit set FF + ED + carry bit = ED 
+3
source

All Articles