110k views
17 votes
Write a procedure ConvertToBinary that takes an input as a number from 0 to 16 (including 0 but not 16) and converts it to a binary number. The binary number should be returned as a list.

2 Answers

6 votes

Final answer:

To convert a number from 0 to 15 into a binary representation, you can use a procedure called ConvertToBinary. This algorithm uses the modulo operator and floor division to extract the binary digits and stores them in a list.

Step-by-step explanation:

ConvertToBinary Procedure

The ConvertToBinary procedure takes a number as the input parameter. It initializes an empty list, binary_list, to store the binary digits. Then, it uses a while loop to perform the conversion process. In each iteration, the remainder of the number divided by 2 is added to the binary_list using the append function. Finally, the list is reversed and returned as the binary representation of the input number.

def ConvertToBinary(num):
binary_list = []
while num > 0:
binary_list.append(num % 2)
num = num // 2
binary_list.reverse()
return binary_list

# Testing the procedure
print(ConvertToBinary(10)) # Output: [1, 0, 1, 0]



User Hari Rao
by
4.5k points
7 votes

Final answer:

To convert a number from 0 to 15 to binary, use the ConvertToBinary procedure that follows an algorithm of binary division.

Step-by-step explanation:

To convert a number from 0 to 15 to binary, we can use the concept of binary division. Here is a procedure, ConvertToBinary, that takes an input number and converts it to a binary number:



Algorithm:

Initialize an empty list to store the binary digits.

Divide the input number by 2, and append the remainder (0 or 1) to the list.

Repeat the above step until the input number becomes 0.

Reverse the list to get the binary number representation.



For example, if the input number is 9, the binary representation would be:

9 / 2 = 4 remainder 1

4 / 2 = 2 remainder 0

2 / 2 = 1 remainder 0

1 / 2 = 0 remainder 1



Reversing the list gives us the binary number: 1001.

User Gurucharan M K
by
4.7k points