×

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking function is IP addressing. Finding the network or host ID using a subnet is a crucial operation for a network engineer when issuing IP numbers.

Simple activities are easier to complete when you have a firm grasp of the fundamentals. We will go over how to translate an IP address into binary in this part.

Converting IP Address into Binary

Here are the methods for memorizing-free binary conversion of a decimal IP address.

Start with the number 1 and count from right to left to help you remember values. Multiply that amount seven times.

  • Start, for instance, with 1 on the right side. The second number will be twice as large as the first, or 1*2=2. Double the previous number (2) to get the third number, which equals 4 (2*2). For the fourth number, multiply the previous number (4) by two to get eight. Continue until the original number has been multiplied by seven times.
  • Arrange the values row-wise after seven times of doubling the number. because we'll give the values either a 0 or a 1.
  • We will take the string of integers and work our way clockwise around them in order to translate the IP address into binary. We ask, "Can I remove this number from the decimal remaining?" for each value. Put 1 there if you answered "yes," otherwise, put 0.
  • Another option to enter 0 or 1 is to add them together to obtain the IP address' decimal value. Put 1 below those values and 0 below the other values if we arrived at the decimal value by adding three values.

Example

As an illustration, we must translate the following IP address into binary.

192.168.32.2

Each symbol denotes an 8-bit value, or a 32-bit IP address.

8-bit data should be represented by 2x, where x stands for x+1, x+2, x+3, etc. Write the values in 8-bit format.

2^0 = 1

2^1 = 2

2^2 = 4

2^3 = 8

2^4 = 16

2^5 = 32

2^6 = 64

2^7 = 128

1          2          4          8          16        32        64        128

After adding 64 and 128 to reach 192, we shall write 1-1 under 64 and 128 and 0 under the remaining integers. As a result, the binary representation of 192 is:

192: 00000011

The numbers 8, 32, and 128 sum up to 168, thus we'll put 1-1 after 8, 32, and 128. As a result, the binary representation of 168 is:

168: 00010101

Likewise, the binary representation of 32 is:

32: 00000100

Likewise, the binary representation of 2 is:

2: 01000000

Keep in mind that each segment's binary should be written backwards when the IP is combined in binary. As a result, IP 192.168.32.2 is represented in binary as 11000000.10101000.00100000. 00000010.

//
import java.util.Scanner;   
public class ITBC   
{   
public static void main (String args[])   
{   
Scanner sr = new Scanner(System.in);   
System.out.println("Please enter an IP Address.");   
//read s address from the user   
String st = sr.nextLine();   
//split s address by dot(.)   
String[] octetArray = st.split("\.");   
for (String string : otArray)   
{   
//determines a string's primitive data type. 
int ot = Integer.parseInt(st);   
//translates a binary st from an integer 
String bO = Integer.toBinaryString(octet);   
//displays the appropriate IP address binary string. 
System.out.println(bO);   
}   
}  
}  

Output:

Please enter an IP Address. 
192.168.32.2 
11000000 
10101000 
100000 
10

Using IP Address java library

It is an open-source Java library that manages subnets and IP addresses. Both IPv4 and IPv6 addresses are compatible.




com.github.seancfoley


ipaddress


5.3.4





//


import java.util.Scanner; 


import java.util.NoSuchElementException; 


import inet.ipaddr.AddressStringException; 


import inet.ipaddr.IPAddress; 


import inet.ipaddr.IPAddressString; 


public class CITB 


{ 


public static void main(String args[])  


{ 


try(Scanner sr = new Scanner(System.in))  


{ 


System.out.print("Enter IP address: "); 


while(true)  


{ 


String sc = scan.next(); 


IPAS s = new IPAS(s); 


IPA address = s.toAddress(); 


System.out.println(address + " is equivalent to " + address.toBS()); 


} 


}  


catch (ASException e) 


{ 


System.out.println("invalid format: " + e.getMsg()); 


}  


catch(NoSuchElementException e)  


{ 


} 


} 


}

Output 1:

Enter IP: 235.145.38.12 
235.145.38.12 is equivalent to 11101011100100010010011000001100 

Output 2:

Enter IP: a:b:c:d:e:f:a:b 
a:b:c:d:e:f:a:b is equivalent to 00000000000010100000000000001011000000000000110

Related Topics

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

2 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Java Binary Tree

The non-linear data structure known as a binary tree is a type of tree, and because it stores data in a hierarchical manner, it is mostly utilised for finding and...

7 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Process and Thread in Java

Process It is a program that is running on your computer. The process is a heavy-weight, which takes memory separately to other processes. The process may be a small background task like spell-checker; it...

11 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.