convert a java.net.InetAddress to a long

别说谁变了你拦得住时间么 提交于 2019-12-05 16:12:54

& 0xff blocks sign extension during conversion from byte to int, but your expression also contains conversion from int to long and you need to block sign extension during this conversion as well:

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

Alternatively, you can convert from byte to long in a single step, by marking the second operand of & 0xff operation as long using l suffix:

final long pumpeIPAddress =
      ((pumpeIPAddressRaw [0] & 0xFFl) << (3*8)) + 
      ((pumpeIPAddressRaw [1] & 0xFFl) << (2*8)) +
      ((pumpeIPAddressRaw [2] & 0xFFl) << (1*8)) +
      (pumpeIPAddressRaw [3] &  0xFFl); 
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();
msteiger

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!