binary

  1. php位运算
    <?php
    # 左移
    $a = 0b0111;
    $b = $a << 1;
    //($b = 0b1110)
    # 右移
    $a = 0b1110;
    $b = $a >> 1;
    //($b = 0b0111)
    # 按位与
    $a = 0b1110;
    $b = 0b0010;
    $c = $a & $b;
    //($c = 0b0010)
    # 按位或
    $a = 0b1100;
    $b = 0b0010;
    $c = $a | $b;
    //($c = 0b1110)
    # 按位异或
    $a = 0b1100;
    $b = 0b0010;
    $c = $a ^ $b;
    //($c = 0b1110)
    # 按位同或
    $a = 0b1100;
    $b = 0b0010;
    $c = ~($a ^ $b);
    //($c = 0b0001)
    # 按位非
    $a = 0b1111;
    $b = ~$a;
    ($b = 0b0000);
    
  2. php进制

    <?php
    # 10进制
    echo 111;
    # 2进制
    echo 0b111;
    # 8进制
    echo 0111;
    # 16进制
    echo 0x111;
    
  3. php位运算权限判定

    <?php
    //定义权限:111:RWX
    //可读权限向左移两位
    define('R', 1<<2);
    //可写权限向左移一位
    define('W', 1<<1);
    //执行权限不进行位移
    define('X', 1<<0);
    //赋予权限:0b101=5=R|X
    $permission = R|X;
    //验证权限
    echo '可以读:'.(($permission & R)?'Yes':'No').'<br/>';
    echo '可以写:'.(($permission & W)?'Yes':'No').'<br/>';
    echo '可执行:'.(($permission & X)?'Yes':'No');
    
  4. php进制转换

    <?php
    # 2: bin
    # 8: oct
    # 16: hex
    # 10: dec
    # 10转2/8/16
    $a = '987';
    $int2 = decbin($a);
    $int8 = decoct($a);
    $int16 = dechex($a);
    # 其它进制转换同理
    
  5. php字符串转数字

    <?php
    /**
     * 将二进制转换成字符串
     */
    function binstr($str) {
        $arr = explode(' ', $str);
        foreach($arr as &$v){
            $v = pack("H".strlen(base_convert($v, 2, 16)), base_convert($v, 2, 16));
        }
        return join('', $arr);
    }
    
    /**
     * 将字符串转换成二进制
     */
    function strbin($str) {
        $arr = preg_split('/(?<!^)(?!$)/u', $str);
        foreach($arr as &$v){
            $tmp = unpack('H*', $v);
            $v = base_convert($tmp[1], 16, 2);
            unset($tmp);
        }
        return join(' ',$arr);
    }
    
    echo strbin("嘿嘿!");
    echo PHP_EOL;
    echo binstr("111001011001100010111111 111001011001100010111111 111011111011110010000001");
    echo PHP_EOL;
    

results matching ""

    No results matching ""