0

## C語言function 改寫成C#

``````//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&lt;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;
}
}

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;
}
}
``````

C#也是有指標的....

C#要使用指標，請在各個函數前，加上unsafe關鍵字。
elearnet iT邦新手 5 級 ‧ 2013-05-21 15:04:22 檢舉
!!!!!! 原來是unsafe

pajace2001 iT邦研究生 1 級 ‧ 2013-08-28 17:56:06 檢舉
unsafe 出現了~

### 1 個回答

12

iT邦大師 1 級 ‧ 2013-05-21 15:04:37

``````&lt;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 &lt; 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;
}
}
}
``````

Ethan Jhuang iT邦研究生 3 級 ‧ 2013-05-21 16:34:36 檢舉

et54987提到：

copy & paste 再改小部分...

echen688 iT邦研究生 1 級 ‧ 2013-05-21 16:39:25 檢舉

ted99tw iT邦高手 1 級 ‧ 2013-05-21 19:55:05 檢舉