1

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 
1
  • 3
    Just to be clear, is the number stored as an integer or an string? Commented Jan 25, 2019 at 22:42

3 Answers 3

1

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'
Sign up to request clarification or add additional context in comments.

Comments

1

This is a very good source for rotational bit shifts in Python:

https://www.falatic.com/index.php/108/python-and-bitwise-rotation

1 Comment

While this link might provide some limited, immediate help, an answer should include sufficient context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, to make it more useful to future readers with other, similar questions. In addition, other users tend to respond negatively to answers which are barely more than a link to an external site, and they might be deleted.
0

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]

2 Comments

why not just use -1 instead of l? :) (The l also looks like 1 which makes it a bit confusing to look at at first)
Yes, you are right! I'm new in python, didn't knew that. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.