新手上路,最好的見面禮莫過于資源分享了。
畢業(yè)設計中關鍵技術是數(shù)據(jù)壓縮模塊,數(shù)據(jù)傳輸?shù)氖亲止?jié)數(shù)組,卻沒有發(fā)現(xiàn)Java庫中現(xiàn)成的整型于字節(jié)數(shù)組的轉換,雖然Integer包裝類有toBinaryString()之類的靜態(tài)方法使用,但是卻無法直接滿足要求一個整數(shù)與4個字節(jié)數(shù)組的對應,幸好String類有getBytes()幾個重載方法使用,要不然真的就哭死了
記得net中就有BinConverter可以直接使用,而且實現(xiàn)了bytes與int16,int32,char等等多類型的轉換,有點感慨,還是.net方便,呵呵
也許是偶還沒有發(fā)現(xiàn)相關的Java庫,google得也不深入,沒辦法,時間不等人,只好自己實現(xiàn)了一個,經測試,正負數(shù)都OK(PS:google到一個算法,比較搞笑,只有負數(shù)是正確)
?1
public
?
class
?BitConverter?
{
?2
????
?3
????
public
?
static
?
byte
[]?getBytes(
int
?value)
?4
????
{?
?5
????????
byte
[]?bytes?
=
?
new
?
byte
[
4
];
?6
????????bytes[
0
]?
=
(
byte
)(?value?
>>
?
24
?);
?7
????????bytes[
1
]?
=
(
byte
)(?(value?
<<
?
8
)?
>>
?
24
?);
?8
????????bytes[
2
]?
=
(
byte
)(?(value?
<<
?
16
)?
>>
?
24
?);
?9
????????bytes[
3
]?
=
(
byte
)(?(value?
<<
?
24
)?
>>
?
24
?);????????
10
????????
return
?bytes;????????????
11
????}
?????????
12
13
????
public
?
static
?
int
?toInt(
byte
[]?bytes,?
int
?startIndex)
{????????
14
????????
int
?value?
=
?
0
;
15
????????
for
?(
int
?j
=
startIndex;j
<
4
;j
++
)?
{????????????
16
????????????value?
=
?(value?
<<
?
8
)?
|
?(bytes[j]?
&
?
0xFF
);
17
????????}
????????
18
????????
return
?value;????
19
????}
20
}



?2

?3

?4



?5

?6

?7

?8

?9

10

11

12

13



14

15



16

17

18

19

20

只有int版本,有時間了再研究其他數(shù)據(jù)類型的了。
歡迎大家拋磚,期待更加便捷的算法。