3

I'm trying to write a program in Java that will take an IP address and convert to binary.

Here is what I have so far:

import java.util.Scanner;

public class IpConverter{

public static void main (String[]args)
{

    int result;

    String data_in;

    int data_out;

        Scanner scan = new Scanner(System.in);

        try
        {
            System.out.print("Enter an IP address: ");
            data_in = scan.next();

            data_out = Integer.parseInt(data_in, 10);
            System.out.println (data_in + "is equivalent to" + data_out);
        }
        catch (NumberFormatException nfe){
            System.out.println("Wrong data type!");

        }
    }
}
4
  • 2
    Assuming your ips are being entered in dotted.quad format (eg 127.0.0.1), parseint isn't going to give you a full 32bit representation of that, since that's not a valid int. Commented Mar 28, 2012 at 2:17
  • 1
    For future reference, if you select all of your code and press CTRL+K you will get one big code block instead of the many small ones you originally had. Commented Mar 28, 2012 at 2:19
  • Yes, 127.0.0.1 would be the format I want. Commented Mar 28, 2012 at 2:22
  • 1
    There are answers to the same question at stackoverflow.com/questions/1146581/… Commented Mar 28, 2012 at 2:33

5 Answers 5

7

Building on jtahlborn' answer:

byte[] bytes = InetAddress.getByName(data_in).getAddress();
data_out = new BigInteger(1, bytes).toString(2);

Now data_out contains the IP address as a binary number.

Sign up to request clarification or add additional context in comments.

Comments

4

you can use InetAddress to parse the textual representation and convert to a byte[]. you can use BigDecimal to convert a byte[] to a big integer.

Comments

2
Scanner in = new Scanner(System.in);
System.out.println("Please enter an IP Address.");
String ip = in.nextLine();
String[] octetArray = ip.split("\\.");
for (String string : octetArray){
    int octet = Integer.parseInt(string);
    String binaryOctet = Integer.toBinaryString(octet);
    System.out.println(binaryOctet);
}

so for input 10.10.150.1 output will be

1010

1010

10010110

1

5 Comments

The string ip = in.nextLine(); command is giving me an error. "error: cannot find symbol String ip = in.nextLine();"
That's weird, the code is copied directly from my code that ran fine.
Anything else i need to import?Other than java.util.Scanner? I also have java.lang.String imported as well.
Scanner is the only think you should need imported.
Not working, man. You think you could add some more of your code to see if I'm missing anything?
0

If you want to avoid name resolution, you can use the following code that converts an IPv4 address string to a byte array:

String[] octetArray = ipAddressStr.split("\\.");
assert octetArray.length == 4;
byte[] ipAddressBytes = new byte[4];
for (int i = 0; i < 4; ++i) {
    ipAddressBytes[i] = Integer.valueOf(octetArray[i]).byteValue();
}

Comments

0

The open-source IPAddress Java library can do this for you. It can parse various IP address formats, including either IPv4 or IPv6. Disclaimer: I am the project manager of the IPAddress library.

Here is sample code similar to yours:

public static void main(String[] args) {
    try(Scanner scan = new Scanner(System.in)) {
        System.out.print("Enter IP addresses: ");
        while(true) {
            String data_in = scan.next();
            IPAddressString string = new IPAddressString(data_in);
            IPAddress addr = string.toAddress();
            System.out.println(addr + " is equivalent to " + addr.toBinaryString());
        }
    } catch (AddressStringException e){
        System.out.println("invalid format: " + e.getMessage());
    } catch(NoSuchElementException e) {}
}

Example usage:

Enter IP addresses: 1.2.3.4 a:b:c:d:e:f:a:b
1.2.3.4 is equivalent to 00000001000000100000001100000100
a:b:c:d:e:f:a:b is equivalent to 00000000000010100000000000001011000000000000110000000000000011010000000000001110000000000000111100000000000010100000000000001011

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.