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

  1. This is your assurance every one|that every one} games are fair, protected and clear. We also voluntarily submit all our games to unbiased testing with auditors, to ensure that|to make sure that} our RNGs are functioning optimally. The outcomes of all actual money online on line casino games are completely random. 888casino NJ doesn't in any means, shape, or form influence 1xbet korea the outcomes of games. It’s similar to taking part in} slots, card games or table games in Atlantic City, or Las Vegas – we're the real deal.

    ReplyDelete

Post a Comment

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

Threads in Java - yield(), sleep() and join() (Part 4)

Let's say we want to stop the execution of a thread. How do we do this? There are three methods in the Thread class which can be used to stop the execution of a thread. Let us discuss these methods one by one 1. Yield method Suppose there are two threads A and B. A takes 10 minutes to complete a job while B takes only 10 seconds. At first, A and B both are in the RUNNABLE state then Thread Scheduler gives resources to A to run. Now B has to wait for 10 minutes to do a 10 seconds job. This very inefficient. Wouldn't it be great if we have some way to prevent the execution of A in between so that B can run? Fortunately, yield() method helps us in achieving this.  If a thread calls yield() method, it suggests the Thread Scheduler that it is ready to pause its execution. But it depends upon the Thread Scheduler to consider this suggestion. It can entirely ignore it. If a thread calls yield() method, the Thread Scheduler checks if there is any thread with same/high