Jak*_*ans 7 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));
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试过谷歌搜索一些解决方案,但我似乎无法让他们中的任何一个给出与此处相同的结果.
这是我从另一个程序中找到的一个解决方案;
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)))
Run Code Online (Sandbox Code Playgroud)
我正试图btishift key = 0xf0f0f0f0f123456.C代码000000000f0f0f12在调用时给出; ror(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;
}
Run Code Online (Sandbox Code Playgroud)
产生以下输出:
f0123456789abcde ef0123456789abcd def0123456789abc cdef0123456789ab
要在Python中生成ror函数,请参阅这篇优秀文章:http://www.falatic.com/index.php/108/python-and-bitwise-rotation
这个Python 2代码产生与上面的C程序相同的输出:
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)
Run Code Online (Sandbox Code Playgroud)
我在Python中找到的最短方法:(注意这仅适用于整数作为输入)
def ror(n,rotations,width):
return (2**width-1)&(n>>rotations|n<<(width-rotations))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17098 次 |
| 最近记录: |