我想將兩個PHP函數轉換爲Java。稱爲deAdjustId()
第一函數轉換String
到Integer
這樣的:PHP/Java String到整數轉換
輸入: ABCD
deAdjustId()產生:1094861636
deAdjustId()的PHP代碼:
function deAdjustId($data)
{
if (strlen($data) < 4) {
$data = "\x00".$data;
}
$data = strrev($data);
$data = unpack('L', $data);
return $data[1];
}
之後,另一個函數adjustId
可以轉換從deAdjustId()
回到這樣給定的輸入結果:)
adjustId(返回: ABCD
adjustId()的PHP代碼:
function adjustId($id)
{
$data = strrev(pack('L', $id));
$data = bin2hex(ltrim($data));
while (strlen($data) < 6) {
$data = '0'.$data;
}
return hex2bin($data);
}
現在我的問題是:有沒有在Java中做類似的方法?由於Java不支持無符號字節,因此必須有另一種方法來重現此結果。如果有人知道這一點,我會很感激。
一些測試用不同的輸入進行:
Note that adjustId() calculates the value from deAdjustId()!
Test 1:
input: ABCD
deAdjustId(): 1094861636
adjustId(): ABCD
Test 2:
input: ABCDEFGHIJK
deAdjustId(): 1212762699
adjustId(): HIJK
Test 3:
input: Thequickbrownfox
deAdjustId(): 1852206968
adjustId(): nfox
謝謝,你真棒! –
我改變它使用字節數組,就像在你的編輯中一樣,但是我是用我自己的方式做的,不用打擾StringBuilder。我希望你不介意。 –
更好,非常感謝! –