4

我想转换 ajava.net.InetAddress并且我与签名/未签名问题作斗争。这样的痛苦。

我在 Java 中读取从短到字节的转换,反之亦然,为什么字节 b =(字节)0xFF 等于整数-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

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

4

3 回答 3

6

& 0xffbyte在从to转换期间阻止符号扩展int,但您的表达式还包含从intto的转换,long并且您还需要在此转换期间阻止符号扩展:

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

或者,您可以通过将操作的第二个操作数标记为使用后缀来一步转换 from byteto :long& 0xfflongl

final long pumpeIPAddress =
      ((pumpeIPAddressRaw [0] & 0xFFl) << (3*8)) + 
      ((pumpeIPAddressRaw [1] & 0xFFl) << (2*8)) +
      ((pumpeIPAddressRaw [2] & 0xFFl) << (1*8)) +
      (pumpeIPAddressRaw [3] &  0xFFl); 
于 2012-04-10T11:36:11.093 回答
4

I think that the answer by user2660727 is good, because it uses only standard Java, is short and efficient. Correcting a few issues (negative values, buffer length), my suggested solution is:

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();
于 2016-08-05T09:51:40.300 回答
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();
于 2014-02-27T13:48:00.787 回答