* / - 你如何使用+实现XOR? [英] How do you implement XOR using +-*/?

查看:204
本文介绍了* / - 你如何使用+实现XOR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何XOR操作(两个32位整数)可以只使用基本的算术运算来实现?你有做按位依次通过各2个功率分配后,还是有捷径吗?我不关心执行速度这么多介绍一个最简单,最短code。

How can the XOR operation (on two 32 bit ints) be implemented using only basic arithmetic operations? Do you have to do it bitwise after dividing by each power of 2 in turn, or is there a shortcut? I don't care about execution speed so much as about the simplest, shortest code.

编辑:
这不是功课,而是一个谜上 hacker.org 构成。问题的关键是实现具有非常有限的操作基于堆栈的虚拟机上的XOR(类似于 brainfuck 的语言和肯定的 - 无移位或MOD)。使用VM是困难的部分,当然​​虽然由算法是简短变得更加容易。

This is not homework, but a riddle posed on a hacker.org. The point is to implement XOR on a stack-based virtual machine with very limited operations (similar to the brainfuck language and yes - no shift or mod). Using that VM is the difficult part, though of course made easier by an algorithm that is short and simple.

虽然FryGuy的解决方案是聪明的,我得去与我当初的理想(类似于litb的解决方案),因为比较难以在环境中使用为好。

While FryGuy's solution is clever, I'll have to go with my original ideal (similar to litb's solution) because comparisons are difficult to use as well in that environment.

推荐答案

我很抱歉,我只知道向前伸直之一头:

I'm sorry i only know the straight forward one in head:

uint32_t mod_op(uint32_t a, uint32_t b) {
    uint32_t int_div = a / b;
    return a - (b * int_div);
}

uint32_t xor_op(uint32_t a, uint32_t b) {
    uint32_t n = 1u;
    uint32_t result = 0u;
    while(a != 0 || b != 0) {
        // or just: result += n * mod_op(a - b, 2);
        if(mod_op(a, 2) != mod_op(b, 2)) {
            result += n;
        }
        a /= 2;
        b /= 2;
        n *= 2;
    }
    return result;
}

在注释的备选可用于代替如果避免支化。不过话又说回来了,解决的办法是不完全要么快,这使得它看起来陌生人:)

The alternative in comments can be used instead of the if to avoid branching. But then again, the solution isn't exactly fast either and it makes it look stranger :)

这篇关于* / - 你如何使用+实现XOR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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