-1

I have a bit of an challenge before me.

Currently I'm trying to accomplish this process:

  • Feed a decimal, or any number really, into a binary converter

  • Now that we possess a binary string, we must measure the length of the string. (as in, numstr="10001010" - I want the return to count the characters and return "8")

  • Finally, I need to extract a section of said string, if I want to cut out the first half of the string "10001010" and save both halves, I want the return to read "1000" and "1010"

Current Progess:

newint=input("Enter a number:")

newint2= int(newint)

binStr=""

while newint2>0:

    binStr= str(newint2%2) + binStr
    newint2= newint2//2

print (binStr)

newint = input("Enter a binary number:")

temp=newint

power = 0

number = 0

while len(temp) > 0:

    bit=int(temp[-1])
    number = number + bit * 2 ** power
    power+=1
    temp = temp[:-1]
print(number)

//This works for integer values, how do I get it to also work for decimal values, where the integer is either there or 0 (35.45 or 0.4595)?

This is where I'm lost, I'm not sure what the best way to attempt this next step would be.

Once I convert my decimal or integer into binary representation, how can I cut my string by varying lengths? Let's say my binary representation is 100 characters, and I want to cut out lengths that are 10% the total length, so I get 10 blocks of 10 characters, or blocks that are 20% total length so I have 5 blocks of 20 characters.

Any advice is appreciated, I'm a super novice and this has been a steep challenge for me.

Aditi
  • 820
  • 11
  • 27
  • You also have code for converting a bitstring into a number, is that also part of the requirement? – FlyingTeller Mar 12 '18 at 09:20
  • Hi @Derekbv, welcome to Stack Overflow. Can you format your code so that it's more readable? The easiest way is with `Ctrl-K` (or `Cmd-K` on Mac), but you can also use manual 4-space tabs at the start of each line. – Phil Sheard Mar 12 '18 at 09:22

2 Answers2

0

Strings can be divided up through slice notation.

a='101010101010'
>>>a[0]
'1'
>>>a[0:5]
'10101'
>>>a[0:int(len(a)/2)]
'101010'

That's something you should read up on, if you're getting into Python.

uwain12345
  • 356
  • 2
  • 21
0

Here is my suggestion, based on answer from What's the best way to split a string into fixed length chunks and work with them in Python? :

def chunkstring(string, percent):
    length = int(len(string) * percent / 100)
    return ([string[0+i:length+i] for i in range(0, len(string), length)])

# Define a string with 100 characters
a = '0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'

# Split this string by percentage of total length
print(chunkstring(a, 10))   # 10 %
print(chunkstring(a, 20))   # 20 %
Laurent H.
  • 6,316
  • 1
  • 18
  • 40