Tag: PHP

アドレスの変換

  • なんとなく書いたので保存しとく

省略形を戻す

<?php
$ip = '1:2:3::7:8';
var_dump(uncompress($ip));

function uncompress($ip)
{
    $res = array_fill(0, 8, 0);
    $adr = array_reverse(explode(':', $ip));
    foreach ($adr as $k => $v) {
        if ($v === '') {
            break;
        }
        $res[$k] = $res[$k] | hexdec($v);
    }

    $res = array_reverse($res);
    $adr = array_reverse($adr);
    foreach ($adr as $k => $v) {
        if ($v === '') {
            break;
        }
        $res[$k] = $res[$k] | hexdec($v);
    }

    for ($i = 0; $i < count($res); $i++) {
        $res[$i] = sprintf('%04x', $res[$i]);
    }

    return implode(':', $res);
}
<?php
$ip = '1:2:3::7:8';
var_dump(uncompress($ip));

function uncompress($ip)
{
    $res = array_fill(0, 8, 0);
    $adr = explode(':', $ip);

    for ($i = 0; $i <= 1; $i++) { 
        $adr = array_reverse($adr);
        $res = array_reverse($res);
        foreach ($adr as $k => $v) {
            if ($v === '') {
                break;
            }
            $res[$k] = $res[$k] | hexdec($v);
        }
    }

    for ($i = 0; $i < count($res); $i++) {
        $res[$i] = sprintf('%04x', $res[$i]);
    }

    return implode(':', $res);
}
<?php
$ip = '1:2:3::7:8';
var_dump(uncompress($ip));

function uncompress($ip)
{
    $res = array_fill(0, 8, 0);
    $adr = explode(':', $ip);

    $t = 0;
    $b = count($res) - 1;
    while ($t >= 0 && $b >= 0) {
        if ($t >= 0) {
            $v = array_shift($adr);
            if (is_null($v) || $v === '') {
                $t = -1;
            } else {
                $res[$t] = $res[$t] | hexdec($v);
                $t++;
            }
        }
        if ($b >= 0) {
            $v = array_pop($adr);
            if (is_null($v) || $v === '') {
                $b = -1;
            } else {
                $res[$b] = $res[$b] | hexdec($v);
                $b--;
            }
        }
    }

    for ($i = 0; $i < count($res); $i++) {
        $res[$i] = sprintf('%04x', $res[$i]);
    }

    return implode(':', $res);
}

Last-modified: 2010-07-30 (金) 15:57:16 (2637d)