简体   繁体   English

python中位的循环移位(相当于Fortran的ISHFTC)

[英]Circular shift of a bit in python (equivalent of Fortran's ISHFTC)

I want to achieve the equivalent of the ISHFTC function in Fortran using python.我想在 Fortran 中使用 python 实现等效的ISHFTC函数。 What is the best way to do this?做这个的最好方式是什么?

For example,例如,

x = '0100110'
s = int(x, 2)
s_shifted = ISHFTC(s,1,7) #shifts to left by 1
#binary representation of s_shifted should be 1001100

My attempt based on Circular shift in c我基于c 中的 Circular shift 的尝试

def ISHFTC(n, d,N):  
    return (n << d)|(n >> (N - d)) 

However, this does not do what I want.但是,这并不能满足我的要求。 Example,例子,

ISHFTC(57,1,6) #57 is '111001'

gives 115 which is '1110011' whereas I want '110011'给出 115 是 '1110011' 而我想要 '110011'

Your attempted solution does not work because Python has unlimited size integers.您尝试的解决方案不起作用,因为 Python 具有无限大小的整数。

It works in C (for specific values of N , depending on the type used, typically something like 8 or 32), because the bits that are shifted out to the left are automatically truncated.它适用于 C(对于N特定值,取决于所使用的类型,通常类似于 8 或 32),因为向左移出的位会被自动截断。

You need to do this explicitly in Python to get the same behaviour.您需要在 Python 中显式执行此操作以获得相同的行为。 Truncating a value to the lowest N bits can be done be using % (1 << N) (the remainder of dividing by 2 N ).可以使用% (1 << N) (除以 2 N的余数)将值截断到最低的N位。

Example: ISHFTC(57, 1, 6)示例: ISHFTC(57, 1, 6)

We want to keep the 6 bits inside |......|我们想把 6 位保留在里面|......| and truncate all bits to the left.并向左截断所有位。 The bits to the right are truncated automatically, because the these are already the 6 least significant bits.右边的位被自动截断,因为它们已经是 6 个最低有效位。

n                  |111001|
a = n << d        1|110010|
m = (1 << N)      1|000000|
b = a % m         0|110010|

c = n >> (N - d)   |000001|(11001)

result = b | c     |110011|

Resulting code:结果代码:

def ISHFTC(n, d, N):  
    return ((n << d) % (1 << N)) | (n >> (N - d))
          #  ^^^^^^ a
          #             ^^^^^^ m
          #  ^^^^^^^^^^^^^^^^^ b
          #                         ^^^^^^^^^^^^ c
>>> ISHFTC(57, 1, 6)
51
>>> bin(_)
'0b110011'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM