C++: Invalid operands when trying to use array in decimal to binary conversion

3 weeks ago 25
ARTICLE AD BOX

I'm relatively new to C++, and I'm writing a small unit converter that converts decimal numbers to hexadecimal, octal, and binary.

Hex and octal work conceptually using repeated division and remainder.

For the binary conversion, I tried using an array of size 8 to store the bits:

int binary_num[] = {0,2,4,8,16,32,64,128};

However, I now get the following compiler errors:

error: invalid operands of types 'int' and 'int\[8\]' to binary 'operator/' error: invalid operands of types 'int' and 'int\[8\]' to binary 'operator%'

Here is the relevant binary part of my code:

else if (decimal_input < binary_num[0]) { result = decimal_input / binary_num; decimal_input = decimal_input % binary_num; cout << "The result of this conversion in binary is: " << result << '\n'; }

What I want:

Convert a decimal number into its 8-bit binary representation

Store the individual bits in an array

Print the correct result

What I'm unsure about:

Can an array be used directly in division like this?

Is my understanding of the division/remainder method wrong?

How should I properly store the binary digits in an array?

Read Entire Article