Why Do I Get Negative Numbers Instead Of Large Integer Numbers In Some Cases?

Because a lot of internet protocols use unsigned 32-bit integers type. But Delphi's Integer type is signed! 31-bits are used for value, and the last bit is sign. If I load a 32-bit unsigned integer into a Delphi Integer type, the last (32nd) bit is used for the sign. This is the reason why large internet integers look like negative numbers.

Nevertheless this negative number is the same value as 32-bit unsigned integer! The difference is only the representation of this number. If you try to convert this negative number to HEX (or another format), you get the correct value. If you try typecasting this negative value to a larger integer type (e.g. int64), you get the correct value!

For example,

   // Get total bytes in for WAN (changed from PPP in v8.3.x)
  if(SNMPget('' + WAN_ifIndex, Community_Edit.Text,
     IpAddress_Edit.Text, response)) then
          // Cardinal avoids -ve nos
          In_Traffic := Cardinal(StrToInt64(response));
          // Only check first SNMPGet as we bail out here if there's an error
          statusBar.SimpleText := ERR_TXT;
          Screen.Cursor := Save_Cursor;

Negative values are not a bug, only a different representation of the same value of a large number!

Why Do You Not Use Int64 Type For Large Integers?

Because older Delphi compilers do not have this 64-bit integer type and Synapse is compatible with Delphi version 2.0 and 3.0 too! The cardinal type is not the solution, because in these older Delphi versions the cardinal type is only a 31-bit integer. (It is terrible!)

public/howto/bignumbers.txt · Last modified: 2007/11/30 14:30 (external edit)
Driven by DokuWiki Recent changes RSS feed