Java IP Address to String ipv4ToBinaryStr(int ipv4)

Here you can find the source of ipv4ToBinaryStr(int ipv4)

Description

Converts an IPv4 address from integer to a 32 bit binary representation (e.g., "11100100...").

License

Open Source License

Parameter

Parameter Description
ipv4 the IPv4 address to be converted (must be in big endian byte-order)

Return

dotted decimal notation

Declaration

static public String ipv4ToBinaryStr(int ipv4) 

Method Source Code

//package com.java2s;
/**//w w w.j ava 2  s . c om
 * NetUtil
 * Copyright (c) 2014 Frank Duerr
 *
 * NetUtil is part of SDN-MQ. This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

public class Main {
    /**
     * Converts an IPv4 address from integer to a 32 bit binary representation (e.g., "11100100...").
     * @param ipv4 the IPv4 address to be converted (must be in big endian byte-order)
     * @return dotted decimal notation
     */
    static public String ipv4ToBinaryStr(int ipv4) {
        StringBuilder[] strBuilder = new StringBuilder[4];

        for (int i = 0; i < 4; i++) {
            strBuilder[i] = new StringBuilder(0);
            short b = (short) (ipv4 & 0xff);
            ipv4 >>= 8;

            short mask = (short) 128;
            for (int j = 0; j < 8; j++) {
                if ((b & mask) == mask) {
                    strBuilder[i].append('1');
                } else {
                    strBuilder[i].append('0');
                }

                mask >>= 1;
            }
        }

        return (strBuilder[3].toString() + strBuilder[2].toString() + strBuilder[1].toString()
                + strBuilder[0].toString());
    }
}

Related

  1. ipToString(final byte[] address)
  2. ipToString(final byte[] bytes)
  3. IpToString(int address)
  4. IPToString(int intIP)
  5. ipToString(long ip)
  6. ipv4ToStr(int ipv4)
  7. ipv4ToString(byte[] address)
  8. ipV4ToString(int ip)
  9. ipV4ToLong(final String ipaddress)