[ask] String to Binary or oct

Joined
Dec 10, 2011
Messages
1
Reaction score
0
Greetings,
I just studied Python and it looks interesting, and complicated though. I want to know how to convert a string to Binary number or Octal number.
The following is my code so far

###-Start-###
def converter (n, n2):
[tab] p = list(n)
[tab] b=p[0]
[tab] num = ord(b)

[tab] for X in n:
[tab][tab] if (X < 0):
[tab][tab][tab] stop_count = False
[tab][tab] elif(stop_count == True):

[tab][tab][tab] if n2== "bin" :

[tab][tab][tab][tab] r= ''
[tab][tab][tab][tab] d = num /2

[tab][tab][tab][tab] while num > 0:
[tab][tab][tab][tab][tab] r = r + str(num % 2)
[tab][tab][tab][tab][tab] num = num / 2


[tab][tab][tab][tab] a = r[::-1]
[tab][tab][tab][tab] b= [a.zfill(8 )]

[tab][tab][tab] elif n2 == 'oct':
[tab][tab][tab][tab] r= ''

[tab][tab][tab][tab] while num > 0:
[tab][tab][tab][tab][tab] r=r+str(num % 8 )
[tab][tab][tab][tab][tab] num = num / 8

[tab][tab][tab][tab][tab] a = r[::-1]
[tab][tab][tab][tab][tab] b = [a.zfill(3)]

[tab][tab] asd = "".join(b)
[tab][tab] print asd

###-End-###

For instance if I type

converter('ab','bin')
>>>01100010 01100001

with my current code:

converter('ab','bin')
>>>
01100010
00000000


The problem with my code is that I only select [0] index. And I'm using ord() function to convert a character to a decimal instead of a string.
Any experienced-python-er(s) can help? :adore:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top