Skip to main content

Number System Conversions

When we start learning mathematics, the first thing we learn is Numbers (0, 1, 2, 3, ...). Basically, numbers are a set of values used to represent different quantities. For example, we can represent the number of students in a class, the number of viewers watching the soccer world cup final etc.

The numbers we use most frequently are in Decimal Number System. Similarly, there are other number systems which have different digits/characters to represent the quantities.

  1. Decimal Number System - 10 digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  2. Binary Number System - 2 digits (0, 1)
  3. Octal Number System - 8 digits (0, 1, 2, 3, 4, 5, 6, 7)
  4. Hexadecimal Number System - 16 digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F)
You can learn more about the number systems here.

Sometimes, it is required to convert decimal numbers to one of the other number systems and vice versa. Therefore, in this blog post, we will look into the different conversion mechanisms. Though there are different APIs in Java that does for you without any hassle but to grasp the concepts, it is imperative to look at how things work under the hood.

1a. Binary to Decimal conversion

/**
 * This method accepts binary argument and convert it into decimal
 * 
 * @param binary
 * @return decimal equivalent
 */
private static int binaryToDecimal(int binary) {

 // Decimal equivalent
 int decimal = 0;

 // The place determines the exponent of 2
 int place = 0;

 // Divide the number by 10 until true
 while (true) {

  if (binary == 0) {
   break;
  } else {

   int temp = binary % 10;

   // Decimal should be added to its previous value and the 2 raised to the power
   // place
   decimal += temp * Math.pow(2, place);

   // Move to more significant digit
   binary = binary / 10;

   // Increment place for more significant digit
   place++;
  }
 }

 return decimal;
}

1b. Decimal to Binary conversion

/**
 * This method converts decimal input to its binary equivalent
 * 
 * @param decimal
 */
private static void decimalToBinary(int decimal) {

 // Array that will store the binary digits
 int[] binary = new int[40];

 // This variable will store the index of each binary digit
 int index = 0;

 // Divide the decimal by 2 until possible
 while (decimal > 0) {

  // Remainders after dividing the decimal by 2 will be stored
  binary[index++] = decimal % 2;

  // Move forward
  decimal = decimal / 2;

 }

 System.out.print("Decimal to Binary: ");
 // Prints the binary digits in the reverse order
 for (int i = index - 1; i >= 0; i--) {

  System.out.print(binary[i]);
 }
 System.out.println("\n");
}

2a. Octal to Decimal conversion

/**
 * This method converts octal number to its decimal equivalent
 * 
 * @param octal
 * @return decimal equivalent
 */
private static int octalToDecimal(int octal) {

 // Decimal equivalent
 int decimal = 0;

 // The place determines the exponent of 8
 int place = 0;

 // Divide the number by 10 until true
 while (true) {

  if (octal == 0) {
   break;
  } else {

   int temp = octal % 10;

   // Decimal should be added to its previous value and the 8 raised to the power
   // place
   decimal += temp * Math.pow(8, place);

   // Move to more significant digit
   octal = octal / 10;

   // Increment place for more significant digit
   place++;
  }
 }

 return decimal;
}

2b. Decimal to Octal conversion

/**
 * This method converts decimal input to its binary equivalent
 * 
 * @param decimal
 */
private static void decimalToOctal(int decimal) {

 // Array that will store the binary digits
 int[] octal = new int[40];

 // This variable will store the index of each binary digit
 int index = 0;

 // Divide the decimal by 2 until possible
 while (decimal > 0) {

  // Remainders after dividing the decimal by 2 will be stored
  octal[index++] = decimal % 8;

  // Move forward
  decimal = decimal / 8;

 }

 System.out.print("Decimal to Octal: ");
 // Prints the binary digits in the reverse order
 for (int i = index - 1; i >= 0; i--) {

  System.out.print(octal[i]);
 }
 System.out.println("\n");
}

3a. Hexadecimal to Decimal conversion

/* This method converts hexadecimal to decimal equivalent
 * 
 * @param hexadecimal
 * @return decimal equivalent
 */
private static int hexadecimalToDecimal(String hexadecimal) {

 // Allowed characters for a hexadecimal number
 String characters = "0123456789ABCDEFG";

 // Converting the input string to uppercase so that we can match them with the
 // characters easily
 hexadecimal = hexadecimal.toUpperCase();

 // This variable will store the decimal representation of the hexadecimal value
 int decimal = 0;

 for (int i = 0; i < hexadecimal.length(); i++) {

  // Get the character at the ith place in the input string
  char c = hexadecimal.charAt(i);

  // Get the place value of the character c
  int n = characters.indexOf(c);

  // Update the value of decimal
  decimal = 16 * decimal + n;
 }

 return decimal;
}

3b. Decimal to Hexadecimal conversion

/**
 * This method converts decimal to hexadecimal
 * @param decimal
 */
private static void decimalToHexadecimal(int decimal) {

 // Variable to store remainder
 int remainder = 0;

 // This variable will store hexadecimal equivalent
 String hexadecimal = "";

 // Characters in the Hexadecimal number system
 char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

 while (decimal > 0) {

  // Get the remainder by dividing the number by 16
  remainder = decimal % 16;

  // Update the hexadecimal value by prepending with the allowed character at the
  // position signified by the remainder
  hexadecimal = digits[remainder] + hexadecimal;

  // Move forward
  decimal = decimal / 16;
 }

 System.out.print("Decimal to Hexadecimal: " + hexadecimal);
}

Conclusion

In this post, we have gone through the different methods of converting one number system to another without using any Java APIs. You can find the code of these examples on my GitHub repository. Feel free to fork or open issues, if any.

I would love to hear your thoughts on this and would like to have suggestions from you to make it better. Feel free to befriend me on Facebook, Twitter or Linked In or say Hi by email.

Happy Coding 😊.

Comments

Popular posts from this blog

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects - making connections caching retrying failed requests threading response parsing error handling, and more.  Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from  https://timesofindia.indiatimes.com/rssfeedstopstories.cms  using the Retrofit library. To work with Retrofit, we need three classes -  Model class to map the JSON data Interfaces which defines the possible HTTP operations Retrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation. Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The respon

Threads in Java - CountDownLatch (Part 12)

A CountDownLatch is a synchronizer which allows one thread to wait for one or more threads before starts processing. A good application of  CountDownLatch is in Java server-side applications where a thread cannot start execution before all the required services are started. Working A  CountDownLatch is initialized with a given count which is the number of threads it should wait for. This count is decremented by calling countDown() method by the threads once they are finished execution. As soon as the count reaches to zero, the waiting task starts running. Code Example Let us say we require three services, LoginService, DatabaseService and CloudService to be started and ready before the application can start handling requests. Output Cloud Service is up! Login Service is up! Database Service is up! All services are up. Now the waiting thread can start execution. Here, we can see that the main thread is waiting for all the three services to start before starting its own

I/O in Java - Masterclass (Part 0)

IO in Java Java input and output processes the input and produces the output based on the input. Java uses streams to perform input and output operations. In this masterclass on I/O, we will learn about the nitty gritty details of the File IO/NIO with lots of code examples. You can follow the below trail to dive deep into Java I/O Part 1 - Basics Part 2 - IO vs. NIO Part 3 - try-with-resources Part 4 - Directory Operations Part 5 - File Operations Part 6 - Temporary File Operations All of these posts include code examples to understand the concept. You can find the code of these examples on my  GitHub  repository. Feel free to fork or open issues, if any. I would love to hear your thoughts on this and would like have suggestions from you to make it better.  Feel free to befriend me on  Facebook ,  Twitter  or  Linked In  or say Hi by  email . Happy Coding 😊