python - 按位循环右移

标签 python bitwise-operators

我正在尝试将此 C 函数转换为 Python;

typedef unsigned long var;
    /* Bit rotate rightwards */
    var ror(var v,unsigned int bits) {
        return (v>>bits)|(v<<(8*sizeof(var)-bits));
    }

我已经尝试使用谷歌搜索一些解决方案,但我似乎无法获得与此处相同的结果。

这是我从另一个程序中找到的一个解决方案;

def mask1(n):
   """Return a bitmask of length n (suitable for masking against an
      int to coerce the size to a given length)
   """
   if n >= 0:
       return 2**n - 1
   else:
       return 0

def ror(n, rotations=1, width=8):
    """Return a given number of bitwise right rotations of an integer n,
       for a given bit field width.
    """
    rotations %= width
    if rotations < 1:
        return n
    n &= mask1(width)
    return (n >> rotations) | ((n << (8 * width - rotations)))

我正在尝试 btishift key = 0xf0f0f0f0f123456 。 C 代码在调用时给出 000000000f0f0f12ror(key, 8 << 1) 和 Python 给出; 0x0f0f0f0f0f123456(原始输入!)

最佳答案

您的 C 输出与您提供的函数不匹配。这大概是因为您没有正确打印它。这个程序:

#include <stdio.h>
#include <stdint.h>

uint64_t ror(uint64_t v, unsigned int bits) 
{
    return (v>>bits) | (v<<(8*sizeof(uint64_t)-bits));
}

int main(void)
{
    printf("%llx\n", ror(0x0123456789abcdef, 4));
    printf("%llx\n", ror(0x0123456789abcdef, 8));
    printf("%llx\n", ror(0x0123456789abcdef, 12));
    printf("%llx\n", ror(0x0123456789abcdef, 16));
    return 0;
}

产生以下输出:

f0123456789abcde
ef0123456789abcd
def0123456789abc
cdef0123456789ab

To produce an ror function in Python I refer you to this excellent article: http://www.falatic.com/index.php/108/python-and-bitwise-rotation

This Python 2 code produces the same output as the C program above:

ror = lambda val, r_bits, max_bits: \
    ((val & (2**max_bits-1)) >> r_bits%max_bits) | \
    (val << (max_bits-(r_bits%max_bits)) & (2**max_bits-1))

print "%x" % ror(0x0123456789abcdef, 4, 64)
print "%x" % ror(0x0123456789abcdef, 8, 64)
print "%x" % ror(0x0123456789abcdef, 12, 64)
print "%x" % ror(0x0123456789abcdef, 16, 64)

关于python - 按位循环右移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27176317/

相关文章:

c - 按位左移 (<<) 奇怪的行为

javascript - 为什么 asm.js 会降低性能?

c - 在 C 中应用具有未初始化变量的 XOR 运算符

python - Numpy 按位运算符优先级?

python - 在 Flask API 中处理多个连接

java - 如何将 java.lang.float 编码为 TH3IFMw?

python - 如何在不覆盖 `self` 的情况下模拟基于类的 View 的特定方法?

python - 什么时候应该在 Python 中使用 'assert'?

Python "logging"模块获取日志消息以进行解析

c - 如何在 C 中反转按位与 (&)?