2012-04-10 70 views
3

我想轉換一個java.net.InetAddress,並且我與簽名/未簽名的問題進行了鬥爭。這樣的痛苦。將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 

有誰知道我還有什麼做錯了?

回答

6

& 0xff塊轉換從byteint期間簽署的擴展,但你的表達也包含int轉換long,你需要這個轉換過程中阻止符號擴展,以及:

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

或者,你可以轉換從bytelong在一個步驟中,通過將第二操作數& 0xff操作標記爲long使用l後綴:

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

歡迎來到stackoverflow!爲了使這個問題更好,你可以給出更多關於這個問題的解釋,而不僅僅是發佈代碼嗎?謝謝! – 2014-02-27 14:06:34

1

我認爲,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();