<?php
/**
 * Link         :   http://www.phpcorner.net
 * User         :   qingbing<780042175@qq.com>
 * Date         :   2019-05-23
 * Version      :   1.0
 */

namespace Helper;

class AsciiConvert
{
    /**
     * 将字符或首字母转换成十进制
     * @param string|int $chr
     * @return int
     */
    private static function _chr2Int($chr)
    {
        if (!is_integer($chr)) {
            $chr = ord($chr);
        }
        return $chr;
    }

    /**
     * 将字符或首字母转换成十六进制
     * @param string|int $chr
     * @return string
     */
    private static function _chr2Hex($chr)
    {
        $num = self::_chr2Int($chr);
        $R = "00";
        $lib = "0123456789ABCDEF";
        $i = 1;
        while ($num > 0) {
            $R{$i} = $lib{$num & 15};
            $num = $num >> 4;
            $i--;
        }
        return $R;
    }

    /**
     * 将字符或首字母转换成二进制
     * @param string|int $chr
     * @return string
     */
    private static function _chr2Binary($chr)
    {
        $num = self::_chr2Int($chr);
        $R = "00000000";
        $i = 7;
        while ($num > 0) {
            $R{$i} = $num & 1;
            $num = $num >> 1;
            $i--;
        }
        return $R;
    }

    /**
     * 将字符串转换成十六进制
     * @param string $var
     * @return string
     */
    public static function str2Binary($var)
    {
        $R = [];
        $len = strlen($var);
        for ($i = 0; $i < $len; $i++) {
            array_push($R, self::_chr2Binary($var{$i}));
        }
        return implode('', $R);
    }

    /**
     * 将字符串转换成十六进制
     * @param string $var
     * @return string
     */
    public static function str2Hex($var)
    {
        $R = [];
        $len = strlen($var);
        for ($i = 0; $i < $len; $i++) {
            array_push($R, self::_chr2Hex($var{$i}));
        }
        return implode('', $R);
    }

    /**
     * 二进制转换成字符串
     * @param string $binary
     * @return bool|string
     */
    public static function binary2Str($binary)
    {
        $len = strlen($binary);
        if ($len % 8 != 0) {
            return false;
        }
        if (0 == $len) {
            return "";
        }
        $R = "";
        $startPos = 0;
        while (true) {
            $chr = substr($binary, $startPos, 8);
            $R .= chr(bindec($chr));
            $startPos += 8;
            if ($startPos >= $len) {
                break;
            }
        }
        return $R;
    }

    /**
     * 十六进制转换成字符串
     * @param string $hex
     * @return bool|string
     */
    public static function hex2Str($hex)
    {
        $len = strlen($hex);
        if (0 == $len) {
            return "";
        }
        if ($len % 2 != 0) {
            return false;
        }
        $R = "";
        $startPos = 0;
        while (true) {
            $chr = substr($hex, $startPos, 2);
            $R .= chr(hexdec($chr));
            $startPos += 2;
            if ($startPos >= $len) {
                break;
            }
        }
        return $R;
    }
}