×

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 Wrapper Class

Wrapper class in Java encapsulates a primitive type within an object. In other words, it is a unique mechanism of Java to convert primitive type in to object and object into primitive type....

3 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 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.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.