Indexing: Presenting integer values in a 'n' bit string, turning on bits according to integer value

Question:

I have a list of numbers. Each index has 3 values.

[{24, 17, 22}, {16, 4, 38}, {25, 13, 38}, {32, 18, 15}, {8, 10, 18}]

I am trying to convert them into 39 bit string and turning on bits according to integer values.

For example, {24, 17, 22} means that I should turn on bits 24, 17, 22 among 39 bits.

Sample Code:

p1='000000000000000000000000000001011000000' #39 bit just to get length (39)
for x in range(0, len(mylist), 1):
    a = mylist[x]
    a = ''.join('1' if i in a else '0' for i in range(len(p1)))
    print (len(a))
    print (a)

Output:

39
000000000000000001000010100000000000000
39
000010000000000010000000000000000000001
39
000000000000010000000000010000000000001
39
000000000000000100100000000000001000000
39
000000001010000000100000000000000000000

if we look at numbers {16, 4, 38}, {25, 13, 38} in the list, the last two numbers are 38. Their 39 bit ouput string are 000010000000000010000000000000000000001 and 000000000000010000000000010000000000001. However, the on bits should be at index 38 not 39.

Am I making a mistake?

Asked By: LearningLogic

||

Answers:

It sounds like you bit indices start at 1, but the string indices start at 0. You could check for i+1 in a to shift them all left by one:

mylist=[{16, 4, 38}]
p1='000000000000000000000000000001011000000'
for x in range(0, len(mylist), 1):
    a = mylist[x]
    a = ''.join('1' if i+1 in a else '0' for i in range(len(p1)))
    print (len(a))
    print (a)

Outputs:

000100000000000100000000000000000000010

with bit 38 now activated instead of bit 39

Answered By: user3357118

You need to add an increment while iterating, i.e., i+1

Do this:

a = ''.join('1' if i+1 in a else '0' for i in range(len(p1)))
Answered By: Beta