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');
ejshin1
  • 1,107
  • 6
  • 17
  • 35
  • 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? – Mark Dickinson Aug 10 '17 at 19:26
  • 2
    Possible duplicate of [Python int to binary?](https://stackoverflow.com/questions/699866/python-int-to-binary) – Mark Dickinson Aug 10 '17 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. – ejshin1 Aug 10 '17 at 19:34
  • @MarkDickinson It's not the same problem. I'm converting integer to binary then to String. – ejshin1 Aug 10 '17 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. – Mark Dickinson Aug 10 '17 at 19:36
  • @JohnColeman I think my question was a bit unclear. Just updated it. – ejshin1 Aug 10 '17 at 19:49

2 Answers2

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

Shrikant Shete
  • 319
  • 2
  • 11
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')
John Coleman
  • 51,337
  • 7
  • 54
  • 119