Is there a function that cycle a binary number? for exemple:
100010001000 turns 010001000100
and it turns 001000100010 then 000100010001 and then 100010001000 so on so forth
Is there a function that cycle a binary number? for exemple:
100010001000 turns 010001000100
and it turns 001000100010 then 000100010001 and then 100010001000 so on so forth
If 100010001000 is a string, then it is a sequence in Python.
So, you can use the itertools package which contains a cycle function.
This function can iterate your binary string in cycle:
>>> n = "100010001000"
>>> c = itertools.cycle(n)
>>> next(c)
'1'
>>> next(c)
'0'
>>> next(c)
'0'
>>> next(c)
'0'
>>> next(c)
'1'
...
You can use this function to shift the digits:
>>> c = itertools.cycle(n)
>>> next(c)
'1'
>>> "".join(next(c) for _ in range(len(n)))
'000100010001'
If you repeat the last two operations, you get the cycle (but in the other way).
You can also use slice concatenations, for instance:
>>> n = "100010001000"
>>> n = n[-1:] + n[0:-1]
>>> n
'010001000100'
>>> n = n[-1:] + n[0:-1]
>>> n
'001000100010'
>>> n = n[-1:] + n[0:-1]
>>> n
'000100010001'
If your number is an integer, you can use binary operators, like >>, <<, & and |. To do so, you need to know the length of your binary integer, here it has 12 digits. Just calculate a mask m with all digits set to 1. And do the rotating:
>>> m = int("111111111111", 2)
>>> n = int("100010001000", 2)
>>> bin(n)
'0b100010001000'
>>> n = (n >> 1) | (n << 11) & m
>>> bin(n)
'0b10001000100'
>>> n = (n >> 1) | (n << 11) & m
>>> bin(n)
'0b1000100010'
>>> n = (n >> 1) | (n << 11) & m
>>> bin(n)
'0b100010001'
>>> n = (n >> 1) | (n << 11) & m
>>> bin(n)
'0b100010001000'
This is a very good source for rotational bit shifts in Python:
https://www.falatic.com/index.php/108/python-and-bitwise-rotation
I thought there was a native function, but nevermind, i made this loosey goosey function that works for me
def cycle(n):
return n[-1] + n[:-1]