2014-01-21 213 views
0

在Java中是否有相當於ntohll C++函數?Java等價於ntohll函數

ntohll的參考可以在這裏找到:ntohll function

事情是我需要從64位長的TCP/IP網絡順序轉換爲小端長。

+0

的可能複製? http://stackoverflow.com/questions/1895131/porting-c-code-need-help-with-bitwise-operation-and-pointer-syntax – Daniele

+0

@Maxbester你爲什麼需要這個功能?就像在java中一樣,你不需要關心網絡字節順序。 –

+0

apache commons'EndianUtils' –

回答

4

相當於Java函數爲:長相當於64位

import java.nio.ByteBuffer; 
    import java.nio.ByteOrder; 

    public long ntohll(long convert) 
    { 
      ByteBuffer bbuf = ByteBuffer.allocate(8); 
      bbuf.order(ByteOrder.BIG_ENDIAN); 
      bbuf.putLong(convert); 
      bbuf.order(ByteOrder.LITTLE_ENDIAN); 
      return bbuf.getLong(0); 
    } 
+0

它的竅門。謝謝! – Maxbester

+0

這相當於Zac Howland的答案,但他的版本更快。 –

2

Java已經使用網絡字節順序,所以不需要轉換它們(這就是爲什麼這些函數在Java中不存在的原因)。

更新

既然你正在閱讀的文件是在小尾數位模式,你有,如果你使用的是JDK 1.5 <寫自己(或使用一個庫)。如果你正在使用JDK 1.5或更高版本,可以使用reverseBytes方法爲整數對象:ntohll的

long data = Long.reverseBytes(some_data); 
+0

看到我對user3200809的評論,我需要讀取由C++程序編寫的文件,並且轉換尚未由C++程序完成。 – Maxbester

+0

@Maxbester更新。 –