Challenge 31

🔟

Denary <-> Binary

Open in Code Editor or Copy Instructions
...solutions at bottom of page...

Create 2 functions denToBin and binToDen to convert integers to a binary string and vice-versa respectively.

Examples:

denToBin(12) would return "01100"

denToBin(-12) would return "10100"

binToDen("01100") would return 12

binToDen("10100") would return -12

You may want to pad your numbers up to the nearest byte - e.g. 12 is equivalent to "01100" or "00001100"

Extension:

Test your functions work by looping from -128 to 127 and converting the numbers to binary. Once you are confident that is working, take these results and covert them back to denary, ensuring the number you got at the end was what you started with

Add functionality for working with fixed-point denary - e.g. you could say each number could have 8 bits for the whole part and 8 bits for the decimal part

Solutions

IGCSE 0478 / O-Level 2210 A-Level 9618