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

Threads in Java - Masterclass (Part 0)

Multithreading is a way to introduce concurrency in a program. In any case, if there are parallel paths in our program (parts which do not depend on the result from another part), we can make use of multithreading.
One should exploit this feature, especially with all these multiple core machines nowadays.

Below are a few reasons why we should use multithreading -
1. Keep a process responsive There was once a time when you would print a document in MS Word and the application would freeze for an annoyingly long amount of time until the job finished. Eventually, Microsoft solved this problem by running a printing job parallel to the main thread/ GUI thread.  To be clear though, not only GUI apps but Network services have to keep an ear to the ground for new clients, dropped connections and cancellation requests. In either case, it is critical to do the heavy lifting on a secondary thread to keep the user satisfied. 2. Keep a processor busy Keeping a processor busy can be a tough task e…

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 connectionscachingretrying failed requeststhreadingresponse parsingerror 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 dataInterfaces which defines the possible HTTP operationsRetrofit.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 response is returned as a Call object…

Threads in Java - Basics (Part 1)

Hello everyone, today we are going to discuss one of the most important concepts in Java - Multithreading.
In the first part of this multi-part blog series, we will be discussing the basics of threads, how can we create them? which is the best approach? and many other questions like these. So without further ado, let's get started.
What are threads? Let's say you are Batman (pretty cool, eh? 😊) and your arch-enemy, the master alchemist Ra's al Ghul has brewed a dangerous potion from the Lazarus Pit. To avenge his earlier defeats by the hands of The Dark Knight, he has spread the potions all over the Gotham city.  Now, the only way to save citizens of Gotham is to find the cure of the potion (hidden in the city somewhere) and find Ra's as well before he can devise a new plan to destroy the city.  Batman calls Nightwing (the original Robin) and asks his help in finding Ra's. Batman decides to find the cure of the deadly potion. In the end, both Batman and Robin wer…