//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;
}
//convert d to (x,y)
void d2xy(int n, int d, int *x, int *y) {
int rx, ry, s, t=d;
*x = *y = 0;
for (s=1; s<n; s*=2) {
rx = 1 & (t/2);
ry = 1 & (t ^ rx);
rot(s, x, y, rx, ry);
*x += s * rx;
*y += s * ry;
t /= 4;
}
}
//rotate/flip a quadrant appropriately
void rot(int n, int *x, int *y, int rx, int ry) {
if (ry == 0) {
if (rx == 1) {
*x = n-1 - *x;
*y = n-1 - *y;
}
//Swap x and y
int t = *x;
*x = *y;
*y = t;
}
}
小弟是程式新手,對於指標還不是很熟悉
希望有大大可以教學一下
<pre class="c" name="code">
public static class C2CS
{
unsafe public static int xy2d(int n, int x, int y)
{
int rx, ry, s, d = 0;
for (s = n / 2; s > 0; s /= 2)
{
//C#的boolean並不等於int,故,使用三元運算式模擬C語言boolean的整數型態
rx = (x & s) > 0 ? 1 : 0;
ry = (y & s) > 0 ? 1 : 0;
d += s * s * ((3 * rx) ^ ry);
rot(s, &x, &y, rx, ry);
}
return d;
}
unsafe public static void d2xy(int n, int d, int* x, int* y)
{
int rx, ry, s, t = d;
*x = *y = 0;
for (s = 1; s < n; s *= 2)
{
rx = 1 & (t / 2);
ry = 1 & (t ^ rx);
rot(s, x, y, rx, ry);
*x += s * rx;
*y += s * ry;
t /= 4;
}
}
unsafe public static void rot(int n, int* x, int* y, int rx, int ry)
{
if (ry == 0)
{
if (rx == 1)
{
*x = n - 1 - *x;
*y = n - 1 - *y;
}
int t = *x;
*x = *y;
*y = t;
}
}
}