1

I have file with bitarray that looks like this:

10000000000000000000000000000000000000000000000000000000000000000000001000000

I need to make a sum of bits according to their position in the bitarray: (second bit, second bit + 7, second bit + 14). I tried the code below, but it made a sum only of the first printed value. Can you please guide me on the problem?

    lines = [line.strip() for line in open('test.txt')]
    bitp = range(1,len(lines[0]),7)
    for i in lines:
        for p in bitp:
            bitsum = sum(int(a) for a in i[p])
8
  • You set the size of bitp with the first line only, are all the lines the same length? Commented May 25, 2012 at 13:32
  • Do you have several bitarray lines in the file? Could you please explain "second bit, second bit + 7, second bit + 14" in a more comprehensive way? Commented May 25, 2012 at 13:50
  • @Hooked yes, it's have the same size Commented May 25, 2012 at 13:51
  • @Jan-PhilipGehrcke Looking at the code makes this obvious, he want these chars: line[1::7] Commented May 25, 2012 at 13:52
  • @Jan-PhilipGehrcke: I need sum of the bits in specific positioins: 1,8,15,23,30,etc (so it's position+7) Commented May 25, 2012 at 13:53

1 Answer 1

1

I think you want to store a sum per line? In this case you need a list:

bitsums = list()
with open('test.txt') as fobj:
    for line in fobj:
        bitsums.append(sum(int(c) for c in line.strip()[1::7]))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank's! it's work perfectly. So, the problem was with stripping and list function.

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.