string hex 互转脚本

作者: admin 分类: 未分类 发布时间: 2016-07-01 00:53

支持转换文件 及 字符串
string hex 互转脚本

<?php
$options = getopt('d:e:x:');
if(empty($options)){
        echo <<<EOT
        code by lostwolf :)
Usage:
  $argv[0] -e encode [String or File]  strtohex  
  $argv[0] -d decode [String or File]  hextostr
  $argv[0] -x encode [String or File]  strtoxcode                                
EOT;
echo PHP_EOL;
}

if($options[d]){
        echo hextostr($options[d]) .PHP_EOL;
}

if($options[e]){
        echo strtohex($options[e]) .PHP_EOL;
}
if($options[x]){
        echo strtoxcode($options[x]) .PHP_EOL;
}

function strtohex($field) { 
        if(is_file($field)){
                $field=file_get_contents($field);
        }

  $s=''; 
  foreach(str_split($field) as $c) $s.=sprintf("%02X",ord($c)); 
  return ($s); 
}

function strtoxcode($field) {
                if(is_file($field)){
                $field=file_get_contents($field);
        }
 $field=bin2hex($field);
 $field=chunk_split($field,2,"\\x");
 $field= "\\x" . substr($field,0,-2);
 return  $field;
}

function hextostr($field) { 
        if(is_file($field)){
                $x=file_get_contents($field);
        }
        if(preg_match('#^[[:xdigit:]]{2,}$#i' , $field)){
     $s=''; 
  foreach(explode("\n",trim(chunk_split($field,2))) as $h) $s.=chr(hexdec($h)); 
    return  ($s);
        }
        
        if(preg_match('#^(?:\\\x[[:xdigit:]]{2})+$#i' , $field)){
     return eval("echo \"$field\";");
        }
        
        else{
        exit('Input Error!'.PHP_EOL);
        }
  
} 

?>

hex.bat 放入环境变量目录

@echo off
color a
php C:\gnu\bin\hex.php %*
标签云