首页 > 解决方案 > PHP,如何获取范围内的每个可能的字节序列?

问题描述

我想要范围(x,y)之间的每个可能的字节序列,就像范围(0,0xFFFF )会给我00...... . ... ~FF00000001FFFF

这行得通,但我怀疑有一种更简单的方法可以让我逃脱,有什么建议吗?

<?php
function incbinstring(string $str): string
{
    /*
    if(strlen($str)===0){
        return "\x00";
    }
    */
    $scanCurrent = strlen($str) - 1;
    while ($scanCurrent >= 0) {
        if ($str[$scanCurrent] !== "\xFF") {
            break;
        }
        --$scanCurrent;
    }
    if ($scanCurrent < 0) {
        // they're all \xFF... add new byte and all zeroes
        return str_repeat("\x00", strlen($str) + 1);
    }

    if ($scanCurrent !== strlen($str) - 1) {
        // preceeded by a bunch of \xFF\xFF\xFF , zero them out
        // ps, this can be optimized to a substr()+str_repeat()
        for ($i = strlen($str) - 1; $i > $scanCurrent; --$i) {
            $str[$i] = "\x00";
        }
    }
    // increment the first non-\xFF with 1
    $str[$scanCurrent] = chr(ord($str[$scanCurrent]) + 1);
    return $str;
}


$str = "\x00";
for ($i = 0; $i < 0xFFFF + 600; ++$i) {
    echo bin2hex($str),"\n";
    $str = incbinstring($str);
}

输出,部分

00
01
02
03
04
05
06
07
(...)
f3
f4
f5
f6
f7
f8
f9
fa
fb
fc
fd
fe
ff
0000
0001
0002
0003
0004
(...)
fffb
fffc
fffd
fffe
ffff
000000
000001
000002
000003
000004
000005
000006
000007

标签: phpbyte

解决方案


<?php

  function counterHex ($fromHex, $toHex ) {
        $fromDec = hexdec($fromHex);
        $toHex = hexdec($toHex);
    
        for ($i = $fromHex; $i< $toHex; $i++){
            echo dechex($i) .", ";
        }
    }


   counterHex(1,'ff');

见:http ://sandbox.onlinephpfunctions.com/code/d70d2766297c32039e01dd868e791b476bc92a87


推荐阅读