有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在PHP中像Java一样操作字节

我有一个Java函数,我需要一个PHP中的等效函数。如果有帮助的话,我用这个来解析MD5散列

public static byte[] asBin(String paramString)
{
    if (paramString.length() < 1)
      return null;
    byte[] arrayOfByte = new byte[paramString.length() / 2];
    for (int i = 0; i < paramString.length() / 2; i++) {
      int j = Integer.parseInt(paramString.substring(i * 2, i * 2 + 1), 16);
      int k = Integer.parseInt(paramString.substring(i * 2 + 1, i * 2 + 2), 16);

      arrayOfByte[i] = ((byte)(j * 16 + k));
    }
    return arrayOfByte;
}

现在我得到了这个,但输出结果不一样

function asBin($str){
    if($str == "") return null;
    $bytes = array();
    for($i = 0; $i < strlen($str) / 2; $i++){
        $j = intval(substr($str, $i * 2, $i * 2 + 1), 16);
        $k = intval(substr($str, $i * 2 + 1, $i * 2 + 2), 16);
        $bytes[$i] = intval($j * 16 + $k);
    }
    return $bytes;
}

共 (1) 个答案

  1. # 1 楼答案

    这就是答案(您需要在代码中添加一些更改)

    function asBin($str) {
        $byte_max = 127;
        $byte_min = -128;
        if($str == "") {
            return null;
        }
        $bytes = array();
        for($i = 0; $i < floor(strlen($str) / 2); $i++){
            $j = intval(substr($str, $i * 2, 1), 16);
            $k = intval(substr($str, $i * 2 + 1, 1), 16);
            $value = $j * 16 + $k;
            // emulation byte-overflow in java
            if ($value > $byte_max) {
                $value = $value - $byte_max + $byte_min - 1;
            }
            $bytes[$i] = $value;
        }
        return $bytes;
    }
    

    详细信息

    • 请参阅文档中应如何使用php^{}

    备选答案

    您还可以使用一个映射更改您的函数。 根据您的代码,可能的答案-只需为所有数字对生成php映射:

    function init_bin_map() {
        $byte_max = 127;
        $byte_min = -128;
        $bin_map = array();
        for ($i = 0; $i <= 15; $i++) {
            for ($j = 0; $j <= 15; $j++) {
                $key = strval(dechex($i)) . strval(dechex($j));
                $value = $i * 16 + $j;
                // emulation of overflow in java
                if ($value > $byte_max) {
                    $value = $value - $byte_max + $byte_min - 1;
                }
                $bin_map[$key] = $value;
            }
        }
        return $bin_map;
    }
    
    $bin_map = init_bin_map();
    
    function asBin2($str, $bin_map) {
        $str = strtolower($str);
        if($str == "") return null;
        $bytes = array();
        for ($i = 0; $i < strlen($str) - 1; $i += 2) {
            $key = substr($str, $i, 2);
            $bytes[$i/2] = $bin_map[$key];
        }
        return $bytes;
    }
    

    我们有:

    $bin_map = array(
        "00" => 0,
        "01" => 1,
        ...
        "80" => -128,
        "81" => -127,
        "82" => -126,
        "83" => -125,
        ...
    );