Mega Code Archive

 
Categories / Delphi / Examples
 

How to compare short strings as numbers

// Requires Int64 type. Earliest versions of Delphi may lack it. type a8ch = array[1..8] of char; PA8C = ^a8ch; // pointer type, to above array of characters PI64 = ^Int64; // pointer type, for Int64 numbers // converts short strings (8 chars max) to a number holding ASCII bytes function StrToAsc(s: string): Int64; begin SetLength(s, 8); // increase or decrease to length of 8 Result := PI64(Pointer(PA8C(@(s[1]))))^; end; // Intermediate use of generic Pointer yields no compiler warnings // The compiler translates the characters in the string // first into the array-of-chars type, and then into the numeric type. // The 8 character-bytes is essentially an array of ASCII codes, and // since they ARE a group of adjacent memory cells holding numbers, // they can be directly interpreted as the 8 bytes of an Int64 in one // swoop. So, no time-wasting byte-at-a-time copying loop is needed! // WITH THE PRECEDING PREPARATION, HERE IS THE COMPARER FUNCTION: // Result: positive: s1 is larger // negative: s2 is larger // zero: first 8 characters of strings are the same function CmpShortS(s1, s2: string): Int64; begin Result := StrToAsc(s1) - StrToAsc(s2); end; // The two swoops are the two lower-level function calls :) // Yes, the Result is a C-language kind of value. Useful... //(included for sake of completeness) // interprets a 64-bit number as a sequence of characters function AscToStr(a: Int64): string; begin SetLength(Result, 8); Result := string(PA8C(Pointer(@a))^); end;