2016-04-20 4 views
1

Ich habe eine Java-Funktion und ich brauche eine entsprechende Funktion in PHP. Ich verwende das, um einen MD5-Hash zu parsen, wenn das hilft.Manipulieren Bytes wie Java in PHP

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; 
} 

Für jetzt habe ich das, aber gibt nicht das gleiche aus.

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; 
} 
+0

Oder benutzen Sie einfach [ 'HEX2BIN()'] (http://php.net/manual/en/function.hex2bin.php) – Sammitch

+0

Vielleicht haben Sie den Überlauf (in Java-Code), wenn Sie 'int' in' byte' konvertieren (siehe '(Byte) (j * 16 + k) ') –

Antwort

1

Dies ist die Antwort (Ihre Notwendigkeit, einige Änderungen in Ihrem Code hinzufügen):

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; 
} 

Einzelheiten:

Alternative Antwort:

Auch Sie können Sie mit einer Karte benützen funktionieren.

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; 
} 

Und wir haben: - Basierend auf Ihren Code, mögliche Antwort nur php Karte für alle Paare von Ziffern erzeugen

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