使用 XOR 交换两个指针 [英] Swap two pointers using XOR

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

问题描述

我有一个关于使用 XOR 两个交换两个字符串文字的快速问题.

I have a quick question about using XOR two swap two string literals.

所以我有以下内容:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void intSwap(int *a, int *b){
    *a=*a^*b;
    *b=*a^*b;
    *a=*a^*b;
}


void swapString(char **a, char **b){
    char *temp=*a;
    *a=*b;
    *b=temp;
}

void main(){
    char *s= "ha";
    char *t= "Oh";

    printf("%s and %s \n",s,t); // prints ha Oh
    swapString(&s,&t);
    printf("%s and %s \n",s,t); // prints Oh ha


    int a=10;
    int b=5;
    printf("%d %d\n",a,b); //print 10 5
    intSwap(&a,&b);
    printf("%d %d\n",a,b); //print 5 10
}

如您所见,我对 intSwap 使用了二元运算 XOR.但是,当我尝试用 swapString 做同样的事情时,它不起作用.

As you can see, I used binary operation XOR to for the intSwap. However, when I tried to do the same thing with swapString, it's not working.

我收到错误消息说:对二进制 ^ 的操作数无效(有‘char *’和‘char *’)

I get error message saying: invalid operands to binary ^ (have ‘char *’ and ‘char *’)

你知道如何使用异或来交换两个字符串文字吗?在C中可能吗?先谢谢了!!

Do you know how to use XOR to swap two string literals? Is it possible in C? Thanks ahead!!

推荐答案

没有对指针进行按位运算.唯一可以作用于它们的算术"操作是 +-(以及它们的子子 ++, --+=-=).因此,您需要转换为 intptr_t(或者在执行按位运算时最好是 uintptr_t)并返回.

There are no bitwise operations on pointers. The only "arithmetic" operations that can act on them are + and - (and their childer ++, --, += and -=). So you need to cast to intptr_t (or preferably uintptr_t when doing bitwise operations) and back.

void pointerXorSwap(int **x, int **y){
    uintptr_t a = (uintptr_t)*x;
    uintptr_t b = (uintptr_t)*y;

    a = a ^ b;
    b = a ^ b;
    a = a ^ b;

    *x = (int*)a;
    *y = (int*)b;
}

无论如何,这是一种不好的做法,不会为您节省任何周期.编译器将使用简单的赋值识别交换并为您优化.优秀的编译器甚至可以识别那些 XOR 悲观化,并将它们转换回更高效的 MOV.这里有一些例子.可以看到,上面的函数会编译成如下指令

Anyway, it's a bad practice and won't save you any cycles. The compilers will recognize swaps using simple assignments and optimize it for you. Good compilers even recognize those XOR pessimizations and convert them back to the more efficient MOVs. Here are some examples. As you can see, the above function will be compiled to the following instructions

pointerXorSwap(int**, int**):
        mov     rax, QWORD PTR [rdi]
        mov     rdx, QWORD PTR [rsi]
        mov     QWORD PTR [rdi], rdx
        mov     QWORD PTR [rsi], rax
        ret

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

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