gpt4 book ai didi

python - 按位循环右移

转载 作者:太空狗 更新时间:2023-10-29 21:39:46 24 4
gpt4 key购买 nike

我正在尝试将此 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;
}

产生以下输出:

f0123456789abcdeef0123456789abcddef0123456789abccdef0123456789ab

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com