Formatting to different bases - Answers
You can use the format method of a string object to easily convert between different bases:
'b' outputs in banry (base 2).
'o' outputs to oct (base 8).
'd' outputs to denary (base 10).
'x' outputs to hex (base 16) using lowercase letters.
'X' outputs to hex (base 16) using uppercase letters.
For example:
print("The binary form of 35 is {0:b}".format(35))
displays
The binary form of 35 is 100011
Q1. Display in a suitable sentence the binary form of 55.
print("The binary form of 55 is: {0:b}".format(55))
Q2. Display in a suitable sentence the binary form of 116.
The binary form of 116 is: 1110100
Q3. Display in a suitable sentence the oct form of 73.
print("The oct form of 73 is: {0:o}".format(73))
Q4. Display in a suitable sentence the hex form of 91 using lower case letters for the hex number.
print("The hex form of 91 using lower case letters is: {0:x}".format(91))
Q5. Display in a suitable sentence the hex form of 255 using upper case letters for the hex number.
print("The hex form of 255 using upper case letters is: {0:X}".format(255))
Q6. Display in a suitable sentence the hex form of 255 using upper case letters for the hex number. The number should be displayed in a field 10 characters wide and be right hand justified.
print("The hex form of 255 using upper case letters is: {0:10X}".format(255))
Q7. Display in a suitable sentence the hex form of 255 using upper case letters for the hex number. The number should be displayed in a field 6 characters wide and be left hand justified.
print("The hex form of 255 using upper case letters is: {0:<6X}".format(255))
Q8. Display in a suitable sentence the hex form of 255 using upper case letters for the hex number. The number should be displayed in a field 12 characters wide and be center justified.
print("The hex form of 255 using upper case letters is: {0:^12X}".format(255))
Q9. Display 289 as a decimal number, in a field 15 characters wide, center justified.
print("The decimal form of 289 using upper case letters is: {0:^15d}".format(289))
Q10. Test your neighbour. Write your own formatting problems with a correct and fully-checked solution. Then challenge your neighbour to write the code to format the numbers as you want them.
Students practise setting and solving problems on each other.