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:
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: