2014-11-25 187 views
0

我必須將3個字節的數據壓縮到兩個字節。 3字節數據包括日期在一個字節中,小時在另一個字節中,最後分鐘在另一個字節中,所以我有3個字節的數據。我可以只將這些數據翻轉成兩個字節。如何在java中將三個字節數據壓縮成兩個字節

謝謝,

+0

請發佈您迄今爲止的代碼。 – 2014-11-25 11:35:29

回答

0
  • 分鐘的範圍從0到59,以便數可以存儲在6 位(6位=> 0至63)
  • 時間是從0到23的數 可以存儲在5位(5位=> 0到31)
  • 天...錯誤...從0到6?讓我們來看看這個。 2個字節= 16位,減去其他位,所以你剩下5位,這已經足夠了。

收拾你3個字節的數據分爲二,你要派位:6 我會0位設置到5分鐘,位至10小時,和位離開的一天數。

所以收拾位的計算公式爲:

packed=minutes+hours*64+days*2048 

要拿回你的未壓縮數據:

minutes=packed & 63 
hours=(packed & 1984)/64 
days=(packed & 63488)/2048 
+0

感謝您的快速回復。但我有十六進制數據,所以我需要使用字節緩衝區將其轉換爲字節,然後必須應用翻轉 – user3518959 2014-11-25 11:53:03

0

我假設你需要從1-31日,小時從0-23和從0到59分鐘,因此您需要一天5位,小時5位和分鐘6位。這正好是16位。你應該把5位(日)和前3位爲小時到您的第一個字節和小時剩下的2位和6位的分進入第二個字節:

int day = 23; 
int hour = 15; 
int minute = 34; 
byte fromint_dh = (day << 3) | (hour >> 2); 
byte fromint_hm = ((hour & 0x03) << 6) | (minute); // take the last two bits from hour and put them at the beginning 

.... 
int d = fromint_dh >> 3; 
int h = ((fromint_dh & 0x07) << 2) | ((fromint_hm & 0xc0) >> 6); // take the last 3 bits of the fst byte and the fst 2 bits of the snd byte 
int m = fromint_hm & 0x3F // only take the last 6 bits 

希望這有助於。很容易弄錯位...

+0

嗨,羅爾夫,讓我清楚地解釋我的問題。 – user3518959 2014-11-25 12:19:10

+0

我有一個int day = Calender.DAY_OF_MONTH; Calendar.HOUR_OF_DAY; Calendar.MINUTE;我已經使用Integer.toHexString()方法將它們轉換爲十六進制。 – user3518959 2014-11-25 12:20:59

+0

現在我有十六進制字符串。然後我給這個十六進制字符串ByteBuffer並獲取字節。現在我得到3個字節,而不是我只打包兩個字節。我希望我清楚嗎? – user3518959 2014-11-25 12:22:35