交换两个指针与内联汇编 [英] Swapping 2 pointers with inline assembly

查看:118
本文介绍了交换两个指针与内联汇编的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用VS 2012开发,在64位操作系统,但输出的可执行文件是32位。最近,我与交换算法摆弄。我没有被实现它基于C;

I'm developing with VS 2012, under 64 bit OS but output executable is 32 bit. Recently I was fiddling with swap algorithm. I did achieve it on C by;

void swap(int *p1, int *p2)
{
  *p1 = *p1 + *p2;
  *p2 = *p1 - *p2;
  *p1 = *p1 - *p2;
}

但我也想做到这一点与内联汇编的(__ ASM)的。我试着用这些codeS;

But I also want to do that with inline assembly (__asm). I tried with these codes;

void aswap(int *p1, int *p2)
{
  __asm {
    mov ebx, p1
    mov ecx, p2
    mov p1, ecx
    mov p2, ebx
  }
}

和测试 aswap()与这些codeS;

and test the aswap() with these codes;

int a = 10;
int b = 200;

// print out the initial values
printf("%x(%d) %x(%d)\n", &a, a, &b, b);

aswap(&a, &b);

// finally print out the swapped values
printf("%x(%d) %x(%d)\n", &a, a, &b, b);

,但各自的地址和(结果)的值不变更。

but the individual addresses and (consequently) the values are not changes.

请帮助我。先谢谢了。

更新1:@ouah

我测试过的掉期()与这些codeS;

I've tested the swap() with these codes;

#include <limits>

int a = INT_MAX;
int b = INT_MAX - 1;
...

和这里是我的截图。我做违法的事与内存?

and here is my screenshot. Did I do something illegal with the memory?

推荐答案

经典的方式做,这是做一个内嵌的交换与几个XOR运算。假设你有EAX 1指针和其他EBX中的code将是:

The classic way to do this is to do an inline swap with several XOR operations. Assuming you have one pointer in EAX and the other in EBX the code would be:

XOR EAX, EBX
XOR EBX, EAX
XOR EAX, EBX

的结果是什么在EAX现在处于EBX,什么是EBX现在在EAX。按照反弹位弄清楚如何工作(和它的全部操作在寄存器中,不需要额外的内存)。

The result is that what was in EAX is now in EBX, and what was in EBX is now in EAX. Follow the bouncing bits to figure out how this works (and it's done entirely in registers, requiring no additional memory).

分享和享受。

这篇关于交换两个指针与内联汇编的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆