Python Forum
Converting Decimal to Binary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting Decimal to Binary
#1
Hello.
My instructor gave us this code to understand. I think I understand what each line does except one line below in bold. Will someone please explain what 'result[0:-p]' is supposed to do for this code? I've commented it out several times and it appears to not affect the outcome. What is this piece of code telling me?

p.s. Thank you all who are out there helping me with questions. You have helped me understand Python much more. V/r Pete



x = float(input('Enter a decimal number between 0 and 1'))
p = 0
count=0
while ((2**p)*x)%1 != 0:
    print('Remainder = '+ str((2**p)*x - int((2**p)*x)))
    p+=1
    count+=1
    
num=int(x*(2**p))
result = ''
if num == 0:
    result = '0'
    
while num > 0:
    result = str(num%2)+result
    print("this result", result)                        
    num = num//2
for i in range (p - len(result)):
    result = '0' + result
    print("hola",result)                                
result = result[0:-p] + '.'  + result[-p:]  #this is the line in question

print("result[0:-p]",result[0:-p])                      
print("result[-p]",result[-p])                          
print("count=",count)                                   
print('The binary representation of the decimal ' + str(x) + ' is ' + str(result))
print("length of binary number is:",len(result))
Reply
#2
This line's effect is to add a dot in result before the p last characters.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Converting an RGBA image to Grayscale and Binary Joni_Engr 3 4,659 Aug-23-2021, 11:54 AM
Last Post: Pedroski55
  Binary to decimal script ThorOdinson12521 1 1,878 May-19-2020, 04:22 PM
Last Post: ThorOdinson12521
  hex file to binary or pcap to binary baran01 1 5,712 Dec-11-2019, 10:19 PM
Last Post: Larz60+
  Converting str to binary ebolisa 1 2,040 Jun-17-2019, 11:50 PM
Last Post: scidam
  testing for Decimal w/o importing decimal every time Skaperen 7 4,488 May-06-2019, 10:23 PM
Last Post: Skaperen
  converting binary b'0x31303032\n' to "1002" string amygdalas 2 2,657 Nov-07-2018, 03:50 AM
Last Post: amygdalas
  Binary for Decimal Numbers emerger 1 2,688 Feb-26-2018, 06:06 PM
Last Post: Larz60+
  Converting an 8-bit binary to decimal WITHOUT the shortcuts EIA 5 7,020 Dec-01-2017, 09:04 AM
Last Post: stranac

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020