Creating A Binary Converter With Java

Computers store information using a system of ones and zeroes known as binary code. Each digit in a binary number is called a bit, and computers use combinations of these bits to represent different types of data, such as numbers, text, images, and sounds.

In this post I will be writing a code for a binary converter.

The main function of this code is to convert integers into binaries.

The code will ask an input from the user, say 42, then this code will convert 42 into its binary form; 101010.

Now let’s get started!

First, Because we will be accepting input from the user, we will have to import Scanner into our code.

which is; import java.util.Scanner;

Second, we create a class called “Converter”, Then a static method called “toBinary” is added with a parameter “int num”.

Now to write code for the converter, an empty String called “Binary” is created. Then we use a while loop to make sure that the number to be input by the user is greater 0, then in the (num%2)+Binary will be assigned to the Binary variable we created earlier. We then end the while loop with num/=2(number we input is divided by 2), Binary is then returned.

After the above, another class with the main method is created where we write codes for accepting input from user by using Scanner and then output the results.

You can see the code below:

Tap on the link below to access the source code:

Leave your questions in the comment box. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *