cdelphihilbert-curve

Calculate XY to D for hilbert curve (Convert C code)


I am trying to convert this bit of code from this wikipedia article from C to Delphi.

//convert (x,y) to d
int xy2d (int n, int x, int y) {
    int rx, ry, s, d=0;
    for (s=n/2; s>0; s/=2) {
        rx = (x & s) > 0;
        ry = (y & s) > 0;
        d += s * s * ((3 * rx) ^ ry);
        rot(s, &x, &y, rx, ry);
    }
    return d;
}

I cannot find an equivalent to the rot function used there


Solution

  • You can use the the Var keyword to pass functions by reference in Delphi, which achieves the same result as passing pointers to ints in the linked C code:

    procedure Rot(N : Integer; RX, RY : Boolean; Var X, Y : Integer);
     var
       T : Integer;
     begin
       If Not RY then
       begin
         If RX then
         begin
           X := N - 1 - X;
           Y := N - 1 - Y;
         end;
           T := X;
           X := Y;
           Y := T;
       end;
     end;
    

    Note that the parameter order has changed. I grouped the parameters passed by reference and those passed by value together. You can use Booleans instead of Integers for RX and RY (make sure you adapt the calling code appropriately though).