0

I would like to count '01' sequence in 5760 binary bits.

First, I would like to combine several binary numbers then count # of '01' occurrences.

For example, I have 64 bits integer. Say, 6291456. Then I convert it into binary. Most significant 4 bits are not used. So I'll get 60 bits binary 000...000011000000000000000000000 Then I need to combine(just put bits together since I only need to count '01') first 60 bits + second 60 bits + ...so 96 of 60 bits are stitched together.

Finally, I want to count how many '01' appears.

s = binToString(5760 binary bits)
cnt = s.count('01');
6
  • 1
    "Is there a function to convert binary into string?" <- I'm not sure what you mean. '01000000000100000000000' is already a string. Can you give examples of the input and output you'd want for such a function? Commented Aug 10, 2017 at 19:26
  • 2
    Possible duplicate of Python int to binary? Commented Aug 10, 2017 at 19:34
  • @MarkDickinson Sorry I translated it into binary. I just updated the value. But, note that I will combine 96 of 60 bits into 5760 binary bits. Commented Aug 10, 2017 at 19:34
  • @MarkDickinson It's not the same problem. I'm converting integer to binary then to String. Commented Aug 10, 2017 at 19:35
  • @ejshin1: What do you mean by "then to String"? A binary representation of an integer is already a string, consisting of the characters '0' and '1'. The solutions in the linked question all return strings. Commented Aug 10, 2017 at 19:36

2 Answers 2

1
num = 6291226
binary = format(num, 'b')
print(binary)
print(binary.count('01'))

If I use number given by you i.e 6291456 it's binary representation is 11000000000000000000000 which gives 0 occurrences of '01'.

If you always want your number to be 60 bits in length you can use

binary = format(num,'060b')

It will add leading 0 to make it of given length

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That's what I was looking for. It worked for me.
Since you have updated the question and as @johnColeman said regarding not using most 4 significant bits I have changed numbers in the answer
0

Say that nums is your list of 96 numbers, each of which can be stored in 64 bits. Since you want to throw away the most 4 significant bits, you are really taking the number modulo 2**60. Thus, to count the number of 01 in the resulting string, using the idea of @ShrikantShete to use the format function, you can do it all in one line:

''.join(format(n%2**60,'060b') for n in nums).count('01')

Comments

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.