In this tutorial, we show you how to convert an IP address to its decimal equivalent in Java, and vice versa. For examples :

Bash
255.255.255.255  <->  4294967295
192.168.1.2 <-> 3232235778

1. IP Address to Decimal

We show you two ways to convert an IP address to a decimal number

  1. Normal power of 256
  2. Bit shifting

1.1 First Example – Power of 256
The IP address is “base 256”, to convert 192.168.1.2 to decimal (base 10) the formula is:

Bash
192 x (256)^3 + 168 x (256)^2 + 1 x (256)^1 + 2 (256)^0 = ?
3221225472 + 11010048 + 256 + 2 = 3232235778
Java
  public long ipToLong(String ipAddress) {

	String[] ipAddressInArray = ipAddress.split("\\.");

	long result = 0;
for (int i = 0; i < ipAddressInArray.length; i++) { int power = 3 - i;
int ip = Integer.parseInt(ipAddressInArray[i]);
result += ip * Math.pow(256, power); } return result;
}

Some developers prefer to use modular like this

Java
result += (Integer.parseInt(ipAddressInArray[i]) % 256 * Math.pow(256, power));

1.2 Second Example - Bit shifting
Review the binary bit shifting graph below :

Java
  public long ipToLong(String ipAddress) {

	long result = 0;

	String[] ipAddressInArray = ipAddress.split("\\.");

	for (int i = 3; i >= 0; i--) {

		long ip = Long.parseLong(ipAddressInArray[3 - i]);

		//left shifting 24,16,8,0 and bitwise OR

		//1. 192 << 24
//1. 168 << 16
//1. 1 << 8
//1. 2 << 0
result |= ip << (i * 8); } return result;
}
Bash
192         00000000 00000000 00000000 11000000
-----------------------------------------------
192 << 24 11000000 00000000 00000000 00000000
Result 00000000 00000000 00000000 00000000
Result |= 11000000 00000000 00000000 00000000 168 00000000 00000000 00000000 10101000
-----------------------------------------------
168 << 16 00000000 10101000 00000000 00000000
Result 11000000 00000000 00000000 00000000
Result |= 11000000 10101000 00000000 00000000 1 00000000 00000000 00000000 00000001
-----------------------------------------------
1 << 8 00000000 00000000 00000001 00000000
Result 11000000 10101000 00000000 00000000
Result |= 11000000 10101000 00000001 00000000 2 00000000 00000000 00000000 00000010
-----------------------------------------------
2 << 0 00000000 00000000 00000000 00000010
Result 11000000 10101000 00000001 00000000
Result |= 11000000 10101000 00000001 00000010

Convert the final binary code to decimal, by hand calculation :) ~

Bash
Result      11000000 10101000 00000001 00000010
index 0 - 31, start from right.
31(1),30(1),29,28,27,26,25,24,23(1),22,21(1),20,19(1),18,17,16,15,14,13,12,11,10,9,8(1),7,6,5,4,3,2,1(1),0
Decimal 1x2^31 + 1x2^30 + 1x2^23 + 1x2^21 + 1x2^19 + 1x2^8 + 1x2^1
2147483648 + 1073741824 + 8388608 + 2097152 + 524288 + 256 + 2
3232235778

2. Decimal to IP Address

We show you two bit shifting and "0xff" masking examples to convert a decimal number back to IP address. The bit shifting is very hard to explain in words, it's better review the binary flows below :

2.1 First Example.

Java
  //ip = 3232235778
public String longToIp(long ip) {
StringBuilder result = new StringBuilder(15); for (int i = 0; i < 4; i++) { result.insert(0,Long.toString(ip & 0xff)); if (i < 3) {
sb.insert(0,'.');
} ip = ip >> 8;
}
return result.toString();
}

Review the bit shifting flows :

Bash
3232235778		11000000 10101000 00000001 00000010

<<Loop 1>>
-----------------------------------------------------------
ip 11000000 10101000 00000001 00000010
& 0xff 00000000 00000000 00000000 11111111
Result 00000000 00000000 00000000 00000010 = 2
Result Append .2
-------------------------> 8
ip >> 8 00000000 11000000 10101000 00000001 {off 00000010} <<Loop 2>>
-----------------------------------------------------------
ip 00000000 11000000 10101000 00000001
& 0xff 00000000 00000000 00000000 11111111
Result 00000000 00000000 00000000 00000001 = 1
Result Append 1.2
----------------> 8
ip >> 8 00000000 00000000 11000000 10101000 {off 00000001} <<Loop 3>>
-----------------------------------------------------------
ip 00000000 00000000 11000000 10101000
& 0xff 00000000 00000000 00000000 11111111
Result 00000000 00000000 00000000 10101000 = 168
Result Append 168.1.2
-------> 8
ip >> 8 00000000 00000000 00000000 11000000 {off 10101000} <<Loop 4>>
-----------------------------------------------------------
ip 00000000 00000000 00000000 11000000
& 0xff 00000000 00000000 00000000 11111111
Result 00000000 00000000 00000000 11000000 = 192
Result Append 192.168.1.2
-----------> 8
ip >> 8 00000000 00000000 00000000 00000000 {off 11000000}

2.2 Second Example.

Java
  //ip = 3232235778
public String longToIp(long ip) { return ((ip >> 24) & 0xFF) + "."
+ ((ip >> 16) & 0xFF) + "."
+ ((ip >> 8) & 0xFF) + "."
+ (ip & 0xFF); }
Bash
3232235778		11000000 10101000 00000001 00000010

1. (ip >> 24) & 0xFF
-----------------------------------------------------------
ip 11000000 10101000 00000001 00000010
-------------------------------------> 24
ip >> 24 00000000 00000000 00000000 11000000 {off 10101000 00000001 00000010}
& 0xff 00000000 00000000 00000000 11111111
Result 00000000 00000000 00000000 11000000 = 192 2. (ip >> 16) & 0xFF
-----------------------------------------------------------
ip 11000000 10101000 00000001 00000010
-------------------------------------> 16
ip >> 16 00000000 00000000 11000000 10101000 {off 00000001 00000010}
& 0xff 00000000 00000000 00000000 11111111
Result 00000000 00000000 00000000 10101000 = 168 3. (ip >> 8) & 0xFF
-----------------------------------------------------------
ip 11000000 10101000 00000001 00000010
--------------------------------------> 8
ip >> 24 00000000 11000000 10101000 00000001 {off 00000010}
& 0xff 00000000 00000000 00000000 11111111
Result 00000000 00000000 00000000 00000001 = 1 4. ip & 0xFF
-----------------------------------------------------------
ip 11000000 10101000 00000001 00000010
& 0xff 00000000 00000000 00000000 11111111
Result 00000000 00000000 00000000 00000010 = 2

3. Java Source Code

Full Java example to demonstrate above scenario :

Java
package com.mkyong.core;

public class JavaBitwiseExample {

	public static void main(String[] args) {

		JavaBitwiseExample obj = new JavaBitwiseExample();

		System.out.println("iptoLong  : " + obj.ipToLong("192.168.1.2"));
System.out.println("iptoLong2 : " + obj.ipToLong2("192.168.1.2")); System.out.println("longToIp : " + obj.longToIp(3232235778L));
System.out.println("longToIp2 : " + obj.longToIp2(3232235778L)); } // example : 192.168.1.2
public long ipToLong(String ipAddress) { // ipAddressInArray[0] = 192
String[] ipAddressInArray = ipAddress.split("\\."); long result = 0;
for (int i = 0; i < ipAddressInArray.length; i++) { int power = 3 - i;
int ip = Integer.parseInt(ipAddressInArray[i]); // 1. 192 * 256^3
// 2. 168 * 256^2
// 3. 1 * 256^1
// 4. 2 * 256^0
result += ip * Math.pow(256, power); } return result; } public long ipToLong2(String ipAddress) { long result = 0; String[] ipAddressInArray = ipAddress.split("\\."); for (int i = 3; i >= 0; i--) { long ip = Long.parseLong(ipAddressInArray[3 - i]); // left shifting 24,16,8,0 and bitwise OR // 1. 192 << 24
// 1. 168 << 16
// 1. 1 << 8
// 1. 2 << 0
result |= ip << (i * 8); } return result;
} public String longToIp(long i) { return ((i >> 24) & 0xFF) +
"." + ((i >> 16) & 0xFF) +
"." + ((i >> 8) & 0xFF) +
"." + (i & 0xFF); } public String longToIp2(long ip) {
StringBuilder sb = new StringBuilder(15); for (int i = 0; i < 4; i++) { // 1. 2
// 2. 1
// 3. 168
// 4. 192
sb.insert(0, Long.toString(ip & 0xff)); if (i < 3) {
sb.insert(0, '.');
} // 1. 192.168.1.2
// 2. 192.168.1
// 3. 192.168
// 4. 192
ip = ip >> 8; } return sb.toString();
} /*
private static void printPrettyBinary(String binary) { String s1 = String.format("%32s", binary).replace(' ', '0'); System.out.format("%8s %8s %8s %8s %n",
s1.substring(0, 8),
s1.substring(8, 16),
s1.substring(16, 24),
s1.substring(24, 32));
}
*/
}

Output

Bash
iptoLong  : 3232235778
iptoLong2 : 3232235778
longToIp : 192.168.1.2
longToIp2 : 192.168.1.2

地址:http://www.mkyong.com/java/java-convert-ip-address-to-decimal-number/

Java – Convert IP address to Decimal Number的更多相关文章

  1. [转]How to convert IP address to country name

    本文转自:http://www.codeproject.com/Articles/28363/How-to-convert-IP-address-to-country-name   Download ...

  2. lwip IP address handling 关于 IP 地址的 操作 API接口

    lwip 2.0.3  IP address handling /** * @file * IP address API (common IPv4 and IPv6) */ 1.u32_t ipadd ...

  3. Convert IPv6 Address to IP numbers (C#)

    URL: http://lite.ip2location.com/ Use the code below to convert the IP address of your web visitors ...

  4. Java Regex match IP address

    Reference: [1] https://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-ex ...

  5. poj 2105 IP Address(水题)

    一.Description Suppose you are reading byte streams from any device, representing IP addresses. Your ...

  6. IP Address 分类: POJ 2015-06-12 19:34 12人阅读 评论(0) 收藏

    IP Address Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 19125   Accepted: 11053 Desc ...

  7. 华东师大OJ:IP Address【IP地址转换】

    /*===================================== IP Address Time Limit:1000MS Memory Limit:30000KB Total Subm ...

  8. poj2105 IP Address(简单题)

    题目链接:id=2105">http://poj.org/problem?id=2105 ----------------------------------------------- ...

  9. IP address/地址 检查

    1.Determine if a string is a valid IP address in C Beej's Guide to Network Programming 2.9.14. inet_ ...

随机推荐

  1. Eclipse Console 加大显示的行数和禁止错误弹出

    在 Preferences-〉Run/Debug-〉Console里边,去掉对Limit console output的选择,或者选择,设置一下buffer size的设定值 禁止弹出: Prefer ...

  2. 算法练习--- DP 求解最长上升子序列(LIS)

    问题描写叙述: 对于2,5,3,1,9,4,6,8,7,找出最长上升子序列的个数 最长上升子序列定义: 对于i<j i,j∈a[0...n] 满足a[i]<a[j] 1. 找出DP公式:d ...

  3. rabbitmq vhost

    参考 http://blog.163.com/sky20081816@126/blog/static/16476102320107173226920/ http://blog.csdn.net/kev ...

  4. Loadrunner脚本编程(2)-VuGen脚本文件的开发过程

    http://www.360doc.com/content/10/0806/13/1698198_44076570.shtml 1.定义测试项目的目标,环境,脚本,测试数据,硬件等.脚本应该符合编码规 ...

  5. eclipse+cygwin+cdt搭建c/c++开发环境

    Cygwin 是一个用于 Windows 的类 UNIX shell 环境. 它由两个组件组成:一个 UNIX API 库,它模拟 UNIX 操作系统提供的许多特性:以及 Bash shell 的改写 ...

  6. PHP进行安全字段和防止XSS跨站脚本攻击过滤(通用版)

    废话不多说,直接贴使用方法和代码: 使用方式:1)写在公共方法里面,随时调用即可.2)写入类文件,使用是include_once 即可 代码: /* 进行安全字段和xss跨站脚本攻击过滤(通用版) - ...

  7. 在win7/8下搭建简易的无线平台

    资料:http://www.cnblogs.com/KeenLeung/p/3482073.html http://www.cnblogs.com/KeenLeung/p/3481998.html 其 ...

  8. php Zend虚拟机

    在前⾯的章节中,我们了解到⼀个PHP⽂件在服务器端的执⾏过程包括以下两个⼤的过程:1. 递给php程序需要执⾏的⽂件, php程序完成基本的准备⼯作后启动PHP及Zend引擎, 加载注册的扩展模块.2 ...

  9. 奇怪的php问题

    <?php echo 999999999999 % 2; ?> 上面的结果居然是-1,不可思议. 999999999999 % 2

  10. XP和Win 7双系统安装说明和注意事项

    安装前说明: 1.先装XP,再装Windows 7,最好不要反过来,不然XP不会把Windows 7的启动管理器给覆盖掉,会麻烦些.总之遵循“旧版本到新版本”安装原则. 2.如果分区不够大,请用以下软 ...