2014-11-04 20 views
0

我正在android上並嘗試讀取tcp套接字,我的tcp服務器正在發送從long數組創建的字節數組。從Android的字節數4字節得到長

在我的android代碼中,我能夠讀取字節數組,但無法從此數組中獲取長整型值。

我的代碼如下。

while (true) 
 
         { 
 
          if(isClosed){break;} 
 
          message = ""; 
 
          //byte[] buffer=new byte[4]; 
 
          if (socket != null) 
 
          { 
 
           try 
 
           { 
 
            int bytesRead; 
 
            InputStream inputStream = socket.getInputStream(); 
 
            byte[] data = new byte[44]; 
 
            while ((bytesRead=inputStream.read()) != -1) 
 
            { 
 
             int count = inputStream.read(data); 
 
             bytearraytolong(data); 
 
            } 
 
           } 
 
           catch (Exception e) 
 
           { 
 
            Log.i("ThreadTask","readFromStream: "+ e.getMessage()); 
 
           } 
 
          } 
 
          else 
 
          { 
 
           Log.i("ThreadTask", "SocketConnection : Cannot Read, Socket is closed"); 
 
          } 
 
         }

private void bytearraytolong(byte[] bf) 
 
{ 
 
    // how to get long here 
 
}

這裏我TCP服務器發送的44個字節的數據,因此有11個長型值,

我想回來一部開拓創新價值我的android應用程序「bytearraytolong」方法

回答

0

我建議看看ByteBuffer(http://developer.android.com/reference/java/nio/ByteBuffer.html)。

您可能還需要檢查以確保服務器序列化類型與您如何反序列化一致;字節順序在某些情況下可能會有所不同。另外,如果您的服務器只發送44個字節,那麼您可能正在處理整數,而不是長整數。長整型是8個字節。

的代碼你正在尋找將

private Long readLongFromBytes(byte[] bytes) { 
    ByteBuffer bb = ByteBuffer.wrap(bytes); 
    return bb.getLong(); 
} 
0

試試這個,但長期是按@Clayton威爾金森說,8個字節的代碼片段。

public static long decodeLong(byte[] input) { 
    long result = 0; 
    for (int i = 0; i < input.length; i++) { 
     if (i >= 8) { 
      break; 
     } 
     result += ((long) input[i] & 0xff) << ((input.length - i - 1) * 8); 
    } 

    return result; 
}