0

I had a question about dividing long binary string to shorter ones.

For example, I am trying to convert...

000000100000000011000000100000000010000000100000000001

to...

000000100000000011
000000100000000010
000000100000000001

So basically, I am looking for a python command so that the program can create new line every 18 digits and if possible, introduce a space between first 7 digits and last 11 digits. And then reverse them all back to longer string.

2 Answers 2

5

This will divide your long string into shorter strings.

>>> s = '000000100000000011000000100000000010000000100000000001'
>>> print('\n'.join([s[i:i + 7] + ' ' + s[i + 7:i + 18] for i in range(0,len(s),18)]))
0000001 00000000011
0000001 00000000010
0000001 00000000001

This will also put in the spaces you mentioned.

To go in the opposite direction, we can do the following:

>>> f = '0000001 00000000011\n0000001 00000000010\n0000001 00000000001'
>>> print(''.join([c for c in f if c in '01']))
000000100000000011000000100000000010000000100000000001
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you very much! Is there a commend to reverse them back together to "s" once thy have been splitted?
Why would you want to do that?
Basically, I am editing binary value to change item number in game. The game uses hex values in the save file. So if I want to convert binary number to hex, I thought I need the long binary string again.
Edited to add the reverse operation. If this helped you, click the check mark button to mark this as accepted so others know it helped you too.
For the replacement f.replace('\n', '').replace(' ', '') is faster, even though the difference would be imperceptible for such small strings.
|
1
val = '000000100000000011000000100000000010000000100000000001'
short_val = ''
for i range(len(val) - 1):
    if i % 16 == 0:
       print(short_val)
       short_val = ''
    else:
       short_val += val[i]

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.