将java.net.InetAddress转换为long

时间:2012-04-10 11:23:23

标签: java byte unsigned signed

我想转换java.net.InetAddress并与签名/未签名的问题进行斗争。这样的痛苦。

我看了convert from short to byte and viceversa in JavaWhy byte b = (byte) 0xFF is equals to integer -1?

结果提出:

     final byte [] pumpeIPAddressRaw =
        java.net.InetAddress.getByName (pumpeIPAddressName).getAddress ();

     final long pumpeIPAddress =
         ((pumpeIPAddressRaw [0] & 0xFF) << (3*8)) +
         ((pumpeIPAddressRaw [1] & 0xFF) << (2*8)) +
         ((pumpeIPAddressRaw [2] & 0xFF) << (1*8)) +
         (pumpeIPAddressRaw [3] &  0xFF);

     android.util.Log.i (
        Application.TAG, "LOG00120: Setzte Pumpen Addresse : " +
        pumpeIPAddress + ":" + pumpeIPPort);

猜猜日志仍然显示:

04-10 13:12:07.398 I/ch.XXXX.remote.Application(24452): LOG00120: Setzte Pumpen Addresse : -1063035647:27015

有人知道我还在做错什么吗?

3 个答案:

答案 0 :(得分:6)

& 0xff在从byte转换为int期间阻止了代码扩展,但您的表达式还包含从intlong的转换,您需要阻止签名此转换期间的延期:

final long pumpeIPAddress =
      (((pumpeIPAddressRaw [0] & 0xFF) << (3*8)) + 
      ((pumpeIPAddressRaw [1] & 0xFF) << (2*8)) +
      ((pumpeIPAddressRaw [2] & 0xFF) << (1*8)) +
      (pumpeIPAddressRaw [3] &  0xFF)) & 0xffffffffl; 

或者,您可以通过使用byte后缀将long操作的第二个操作数标记为& 0xff,在一个步骤中将long转换为l

final long pumpeIPAddress =
      ((pumpeIPAddressRaw [0] & 0xFFl) << (3*8)) + 
      ((pumpeIPAddressRaw [1] & 0xFFl) << (2*8)) +
      ((pumpeIPAddressRaw [2] & 0xFFl) << (1*8)) +
      (pumpeIPAddressRaw [3] &  0xFFl); 

答案 1 :(得分:3)

String ip = "127.0.0.1";
InetAddress inetAddress = InetAddress.getByName(ip);

// ByteOrder.BIG_ENDIAN by default
ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE);
buffer.put(inetAddress.getAddress());
buffer.position(0);
Long longValue = buffer.getLong();

答案 2 :(得分:3)

我认为user2660727 is good的答案,因为它只使用标准Java,所以答案简短而有效。纠正一些问题(负值,缓冲区长度),我建议的解决方案是:

InetAddress bar = InetAddress.getByName(ip);
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES).order(ByteOrder.BIG_ENDIAN);
buffer.put(new byte[] { 0,0,0,0 });
buffer.put(bar.getAddress());
buffer.position(0);
long address = buffer.getLong();