Link to home
Start Free TrialLog in
Avatar of APS NZ
APS NZFlag for New Zealand

asked on

(1998*100)+1 = 3193 !!!

I am working on an accounting system and I need to have a feild which combines the year and month.  I set up a function to get the value required:

function FetchMonth(Dt: TDateTime): LongInt;
var Y,M,D: Word;
begin
     DecodeDate(Dt,Y,M,D);
     Result := (Y*100)+M;
end;

The result, given the date 01/01/1998, is 3193 instead of 199801.  Why???  and how do I get the correct answer?

I tried using a LongInt variable to capture the answer before the result line, but I still got the same incorrect answer.

I am using D1 and Win 3.11.
Avatar of julio011597
julio011597

Would you try this:

Result := Longint(Y) * 100 + M;

If this works (i've not Delphi1 to test), please let me know, and i'll submit an answer with full explanation.
In D2 and it works ....

In D1 it doesn't .... Y*100+M gives wrong result?
   I tried double, but same result....

I know D1 & D2 calculate there date different, but this has nothing to do with it....

Julio, your code also doesn't work...

Regards, Zif.

Sorry JULIO's code DOES Work!!!
Hi,
Julio is right, give him the points please. Let me explain the reason just for colobrating. The reason is the size of the integer in Delphi 1( or in 16 bit windows) the integer is 16 bits wide which you have max number be 65535(unsinged).
However
1998*100+1 = 199801 which is larger than 65535 gives an overflow.
In this case the program performs the following(naturally discards the rest)
(1998*100+1) mod 65536 = 3193
So, by rewriting it as
Longint(1998) * 100 + 1 you tell compiler that the operations be carried out in longint(32 bit type) basis which can hold upto 2^32 unsigned.
Regards,
Igor
ASKER CERTIFIED SOLUTION
Avatar of julio011597
julio011597

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can also use Delphi 3 that you can find it
work right,but under Delphi 1 ,it seems you must
use longint(y) instead of y
jianl, there's nothing going wrong under a technical point of view... did you understand the answer?

BTW, jdthedj, there's another way in order to keep using integers:

var Enc: Integer;
var Y, M: Word;

--/ [encoding] /--
Enc := (Integer(Y) shl 4) and M;
--//--

--/ [decoding] /--
M := Enc and $000F;
Y := (Enc shr 4) and $0FFF;
--//--

For this code to work, i'm assuming: M < 16 and Y < 4096, otherwise they just wouldn't fit in 16 bits.
You'll have an application with Y4K problems :)

BTW, anyone knows if, in that assignment to Y, the "and $0FFF" is really needed?
I.e. has Delphi/OOP the same concerns as C when right-shifting a signed type?
Avatar of APS NZ

ASKER

Thanks for all the help guys!!  I was beginning to think it was a Delphi bug.