PHP / Java字符串到整数转换

时间:2016-01-18 19:24:15

标签: java php

我正在尝试将两个PHP函数转换为Java。第一个名为deAdjustId()的函数将String转换为Integer,如下所示:

输入: 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

2 个答案:

答案 0 :(得分:1)

脱离我的头顶:

int deAdjustId(byte[] s)
{
    int r = 0;
    for (int i = s.length <= 4 ? 0 : s.length - 4; i < s.length; ++i) 
    {
        r = (r << 8) + ((int)s[i] & 255);
    }
    return r;
}

byte[] adjustId(int id)
{
    byte[] ba = new byte[4];
    for (i = 0; i < 4; ++i)
    {
        char c = (char)(id & 255);
        if (c == 0) {
            byte[] ta = new byte[i];
            System.arrayCopy(ba, 4 - i, ta, 0, i);
            ba = ta;
            break;
        }
        ba[3 - i] = (byte)c;
        id = id >>> 8;
    }
    return ba;
}

答案 1 :(得分:0)

public static int deAdjustId(byte[] s) {
    int r = 0;
    for (int i = s.length <= 4 ? 0 : s.length - 4; i < s.length; ++i) {
        r = (r << 8) + ((int) s[i] & 255);
    }
    return r;
}

public static byte[] adjustId(int id) {
    byte[] ba = new byte[4];
    for (int i = 0; i < 4; i++) {
        char c = (char) (id & 255);
        if (c == 0) {
            System.arraycopy(ba, 4 - i, ba, 0, i);
            break;
        }
        ba[3 - i] = (byte) c;
        id = id >>> 8;
    }
    int k = 0;
    label:
    for (int j = 0; j < 4; j++) {
        switch (ba[j]) {
            case 0:
            case 9:
            case 10:
            case 11:
            case 13:
            case 32:
                k++;
                break;
            default:
                break label;
        }
    }
    byte[] output = new byte[ba.length - k];
    System.arraycopy(ba, k, output, 0, output.length);
    return output;
}