1

I have a very long string of bits (500 bits of 0s and 1s only). How do I convert this to decimal in sets of 4 (i.e a nibble of 4 bits)?

I tried the following approach, but it doesn't work (followed from here)

with open("atb.bat","rb") as file:   # atb.bat is the file which contains the string
    data=file.read(4)
with open("out.txt","w") as f:
    f.write(" ".join(map(str,data)))
    f.write("\n")

I expect the output to be 125 integers but end up with only 4 decimal values!

I also tried something like this

p1 = 100000001111100101110011001101100110010 # (for example)
p22 =np.packbits(p1,axis=0)

but doesn't work!

Any ideas? Thanks

ksnf3000
  • 19
  • 3

2 Answers2

1

You can convert strings out of 0's and 1's by the int(inputstring, 2)method: Convert base-2 binary number string to int

So loop over your long inputstring , take 4 chars (which you can do like explained here Split string every nth character?) an pass them to the int() method. Then concat/join the output to a loong outputstring.

Manuel
  • 534
  • 3
  • 9
0
nn = 4    
p12_ = [int(p1[i:i+nn],2) for i in range(0, len(p1), nn)]
ksnf3000
  • 19
  • 3