I had this little homework assignment and I needed to convert decimal to octal and then octal to decimal. I did the first part and could not figure out the second to save my life. The first part went like this:
decimal = int(input("Enter a decimal integer greater than 0: "))
print("Quotient Remainder Octal")
bstring = " "
while decimal > 0:
remainder = decimal % 8
decimal = decimal // 8
bstring = str(remainder) + bstring
print ("%5d%8d%12s" % (decimal, remainder, bstring))
print("The octal representation is", bstring)
I read how to convert it here: Octal to Decimal, but I have no clue how to turn it into code.
Source Code. # Python program to convert decimal into other number systems dec = 344 print("The decimal value of", dec, "is:") print(bin(dec), "in binary.") print(oct(dec), "in octal.") print(hex(dec), "in hexadecimal.") The decimal value of 344 is: 0b101011000 in binary.
Convert Octal to Decimal Worked Examples So 275 in octal is equal to 189.
Conversions of Decimal Fractions to Octal Fractions – The conversion of decimal fraction to octal fraction is similar to decimal fraction to binary fraction. Here we multiply the fraction by 8 instead of 2. Example – Find the octal equivalent of (0.75)10. Number (to be recorded) 0.75 x 8 = 6.00 Thus (0.75)10 = (0.6)8.
Method 1: Slicing To skip the prefix, use slicing and start with index 2 on the octal string. For example, to skip the prefix '0o' on the result of x = oct(42) ='0o52' , use the slicing operation x[2:] that results in just the octal number '52' without the prefix '0o' .
From decimal to octal:
oct(42) # '052'
Octal to decimal
int('052', 8) # 42
If you want to return octal as a string then you might want to wrap it in str
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With