How do you use a return method to convert integers into binary numbers?

193 Views Asked by At

I'm in my first year comp sci class and I'm using Drjava. I have an assignment to have the user input two numbers, both ranging from 0 to 255, convert them to binary numbers, add these numbers, then output their binary version of the sum.

My program should include the following methods:

int[] convertToBinary(int b): 

Translates the parameter to a binary value and returns it stored as an array of ints.

void printBin(int b[]): 

Outputs the binary number stored in the array on one line.

int[] addBin(int a[], int b[]): 

Adds the two binary numbers stored in the arrays, and returns the sum in a new array of ints.

I think I'm supposed to create an array of binary numbers but I'm not sure. If so, I can't figure out how to use arrays in return methods. Any idea on how to tackle this assignment? Thanks.

1

There are 1 best solutions below

0
On

I havn't read your assignment but from the methods you provided you can most likely assume that you should store the binary numbers in arrays of size 8.

Hence 8 bits = 0-255.

To tackle the assignment try start by making a array and in some magical way converting the number into each bit b7 to b0.

Think of the array as in the following format:

[b7, b6, b5, b4, b3, b2, b1, b0]

Where bX is 0 or 1.

There are many ways of solving this problem, you could use the toBinaryString method in the integer class and then parsing the text.

or you could make a simple solution with if statements and a loop.

Try creating some code and work your way around the problem and you should be able to solve it pretty fast the rest, adding two binary numbers etc should be easy once you managed to convert a integer to a int array.