2016-08-01 50 views
0

我已經實現了從字節數組中獲取消息的邏輯。無法獲取全長消息

public getInfo(byte[] hi) { 

     type = .... 

     sequence = .... 

     int ack = .... 

     int lastbyte = ....; 

     int isUTF8byte = .....; 

     actual_msg += (char) hi[CHAR1]; 
     actual_msg += (char) hi[CHAR2]; 
     actual_msg += (char) hi[CHAR3]; 
     actual_msg += (char) hi[CHAR4]; 
     actual_msg += (char) hi[CHAR5]; 
    } 

問題是它只給出了消息的前五個字符。我的意思是如果字節數組包含Hello How are you,我只能得到輸出爲Hello。字節數組具有char消息的第3到第7個字節(5個字節)。

我認爲消息中剩餘字符的邏輯應該位於for循環中,因爲目前我有邏輯來讀取前5個字符。第0到第2個字節對​​於所有消息組是相同的。只有3至7字節是我關心的問題。

我該如何執行此操作?

+1

如果'的byte []'是7個字節長,你如何期待它持有「你好,你好嗎」? – bradimus

+0

不,我的意思是大小不是7個字節。字節數組的字段具有第3至第7字節作爲字符消息。我編輯了我的問題。對不起 – Mark023

+0

它仍然聽起來像你沒有足夠的'字節'。要得到「你好,你好嗎」,你需要使用字節3到19(假設我正確計算)。消息是否限制爲7個字節,或者是否有空間存儲更多數據? – bradimus

回答

1

如果我理解正確你的問題,你要像

public String getMessage(byte[] bytes) { 
    StringBuilder message = new StringBuilder(); 
    int index = 0 
    while (index < bytes.length) { 
     byte[] partOfMessage = Arrays.copyOfRange(bytes, index + 3, index + 7); 
     message.append(new String(partOfMessage , StandardCharsets.UTF_8)); 
     index += 7; 
    } 
    return message.toString(); 
} 
1

我認爲你正在尋找這樣的:

byte [] subArray = Arrays.copyOfRange(bytearray, startpos, endpos); 
String str = new String(subArray, StandardCharsets.UTF_8); 
+0

這是做什麼用的? – Mark023

+0

'byte [] subArray = Arrays.copyOfRange(bytearray,startpos,endpos);' 這會創建一個數組的子數組(提取消息)。 'String str = new String(subArray,StandardCharsets.UTF_8);' 這個轉換就是一個字符串 – beeb