Java:如何将dec转换为32bit int? [英] Java: how to convert dec to 32bit int?

查看:158
本文介绍了Java:如何将dec转换为32bit int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中将IP地址的十进制表示形式转换为32位整数值?
我使用InetAddress类和getLocalHost方法获取IP地址:

How to convert decimal presentation of an ip address to 32bit integer value in java? I use InetAddress class and getLocalHost method to obtain an IP adress:

public class getIp {

public static void main(String[] args) {
   InetAddress ipaddress;

    try {
      ipaddress=InetAddress.getLocalHost();
       System.out.println(ipaddress);
        }
      catch(UnknownHostException ex)
      {
        System.out.println(ex.toString()); 
      }


    }
}

我应该将结果转换为32位整数值,然后再转换为字符串,该怎么办?
谢谢!

Than I should convert the result to 32bit integer value and than to string, how do I do that? Thanks!

推荐答案

如果IP地址为IPv6,它将无法正常工作。
否则,对于Sun / Oracle实施和IPv4,您可能会变得肮脏:
ipaddress.hashCode()-可行,但可能会中断

If the IP address is IPv6, it won’t work. Otherwise for the Sun/Oracle implementation and IPv4, you can play dirty: ipaddress.hashCode()works but may break in the future, therefore not recommended.

否则(推荐): int ipv4 = ByteBuffer.wrap(addr.getAddress()) .getInt()

这篇关于Java:如何将dec转换为32bit int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆