yms/transcode.php
changeset 0 9997bee9ad03
equal deleted inserted replaced
-1:000000000000 0:9997bee9ad03
       
     1 <?php
       
     2 
       
     3 define('CHARSET_HEX', '0123456789abcdef');
       
     4 define('CHARSET_MODHEX', 'cbdefghijklnrtuv');
       
     5 define('CHARSET_BASE64', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=');
       
     6 
       
     7 function yms_modhex_encode($str)
       
     8 {
       
     9   if ( !preg_match('/^[' . CHARSET_HEX . ']+$/', $str) )
       
    10     $str = yms_hex_encode($str);
       
    11   
       
    12   return strtr($str, '0123456789abcdef', 'cbdefghijklnrtuv');
       
    13 }
       
    14 
       
    15 function yms_modhex_decode($str)
       
    16 {
       
    17   if ( !preg_match('/^[' . CHARSET_MODHEX . ']+$/', $str) )
       
    18     return false;
       
    19   
       
    20   return strtr($str, 'cbdefghijklnrtuv', '0123456789abcdef');
       
    21 }
       
    22 
       
    23 function yms_hex_decode($str)
       
    24 {
       
    25   if ( !preg_match('/^[' . CHARSET_HEX . ']+$/', $str) )
       
    26     return false;
       
    27   
       
    28   if ( strlen($str) % 2 != 0 )
       
    29     return '';
       
    30   
       
    31   $return = '';
       
    32   for ( $i = 0; $i < strlen($str); $i+=2 )
       
    33   {
       
    34     $chr = substr($str, $i, 2);
       
    35     $return .= chr(intval(hexdec($chr)));
       
    36   }
       
    37   return $return;
       
    38 }
       
    39 
       
    40 function yms_hex_encode($str)
       
    41 {
       
    42   $return = '';
       
    43   for ( $i = 0; $i < strlen($str); $i++ )
       
    44   {
       
    45     $chr = dechex(ord($str{$i}));
       
    46     if ( strlen($chr) < 2 )
       
    47       $chr = "0$chr";
       
    48     $return .= $chr;
       
    49   }
       
    50   return $return;
       
    51 }
       
    52 
       
    53 function yms_tobinary($str)
       
    54 {
       
    55   if ( preg_match('/^[' . CHARSET_HEX . ']+$/', $str) )
       
    56   {
       
    57     return yms_hex_decode($str);
       
    58   }
       
    59   else if ( preg_match('/^[' . CHARSET_MODHEX . ']+$/', $str) )
       
    60   {
       
    61     return yms_hex_decode(yms_modhex_decode($str));
       
    62   }
       
    63   else if ( preg_match('#^[' . CHARSET_BASE64 . ']+$#', $str) )
       
    64   {
       
    65     return base64_decode($str);
       
    66   }
       
    67   return $str;
       
    68 }
       
    69 
       
    70 function yms_randbin($len)
       
    71 {
       
    72   $ret = '';
       
    73   for ( $i = 0; $i < $len; $i++ )
       
    74   {
       
    75     $ret .= chr(mt_rand(0, 255));
       
    76   }
       
    77   return $ret;
       
    78 }
       
    79