I am trying to set a unique id using GetTickCount
I am doing the following
var
UniqueID : DWORD;
LastUniqueID : DWORD;
uniqueString : string;
begin
UniqueID := GetTickCount;
LastUniqueID := GetTickCount + 1000;
uniqueString := intTostr(LastUniqueID);//or UniqueID
end;
I got invalid integer value on uniqueString := intTostr(LastUniqueID);
Project project1.exe raised exception class EConvertError with message ''2312357250' is not a valid integer value'.
what am I doing wrong ?
Unfortunately, you have shown code that does not match the error message that you report. Your actual code calls StrToInt
rather than IntToStr
. I know this because that error message is produced by calls to StrToInt
rather than IntToStr
.
Your code looks more like this:
UniqueID := StrToInt('2312357250');
Note that StrToInt
returns a signed 32 bit integer type. Valid values are in the range -2,147,483,648 to 2,147,483,647. Your value is outside the valid range for Integer
, hence the error.
If you want a simple way to side step all these range issues, then use Int64
instead of DWORD
or Integer
, and call StrToInt64
.
Furthermore, these lines are troublesome:
UniqueID := GetTickCount;
LastUniqueID := GetTickCount + 1000;
You make two distinct calls to GetTickCount
. These two calls may yield different values. Indeed, if GetTickCount
rolls over, then the second call may return a value that is less than the first one.
Yet more troubles surround GetTickCount + 1000
. If GetTickCount
returns a value close to the upper limit, then you will encounter integer overflow, which may have results that you don't expect. Use GetTickCount64
to avoid that pitfall.
However, I remain to be convinced that the system tick count can is a good way to generate a unique ID. Depending on your requirements, this may well be a poor solution to your problem, whatever it is. On the face of it, your code appears to preclude requesting a unique ID less than a second later than the previous time you requested one. Of course, without knowing your requirements it is hard to recommend an alternative.