Home

Algorithmic Advent: 10 – Hexadecimal representation

Published on 10 Dec 2010. Tagged with php, algorithmicadvent.

/**
 * Displays data in hexadecimal encoding
 *
 * @param string $data Data to display in hex viewer
 * @return string Hex representation of input data
 */
function hexView($data)
{
    $data = (string) $data;

    $chunklen = 16;
    $l = strlen($data);
    
    if ($l === 0) {
        return '';
    }

    $ret = '00000000  ';

    $origLine = '';

    $lc = 0; // line counter
    $rc = 0; // row counter

    for ($i = 0; $i < $l; $i++) {
        $ret .= sprintf('%02X', ord(substr($data, $i, 1)));

        $n = ord(substr($data, $i, 1));

        if ($n <= 32 || $n === 127) {
            $origLine .= '.';
        } else {
            $origLine .= substr($data, $i, 1);
        }

        $rc++;
        if ($rc === 2) {
            $origLine .= '';
            $ret .= ' ';
            $rc = 0;
        }

        if (($i + 1) % $chunklen === 0) {

            $ret .= ' ' . $origLine;
            $origLine = '';

            $ret .= "\n";
            $lc++;

            if ($lc === 4) {
                $ret .= "\n";
                $lc = 0;
            }
            $rc = 0;

            if ($i < $l - 1) {
                $ret .= sprintf('%08X  ', $i + 1);
            }
        }        
    }

    if ($origLine !== '') {
        $k = $chunklen - ($i) % $chunklen;

        for ($i = 0; $i < $k; $i++) {
            $ret .= '  ';

            if ($i % 2 === 0) {
                $ret .= ' ';
            }
        }

        $ret .= ' ' . $origLine;
    }

    return $ret;
}



header('Content-Type: text/plain;');

$data = '';

for ($i = 0; $i <= 255; $i++) {
    $data .= chr($i);
}

echo hexView($data);

Output:

00000000  0001 0203 0405 0607 0809 0A0B 0C0D 0E0F  ................
00000010  1011 1213 1415 1617 1819 1A1B 1C1D 1E1F  ................
00000020  2021 2223 2425 2627 2829 2A2B 2C2D 2E2F  .!"#$%&'()*+,-./
00000030  3031 3233 3435 3637 3839 3A3B 3C3D 3E3F  0123456789:;<=>?

00000040  4041 4243 4445 4647 4849 4A4B 4C4D 4E4F  @ABCDEFGHIJKLMNO
00000050  5051 5253 5455 5657 5859 5A5B 5C5D 5E5F  PQRSTUVWXYZ[\]^_
00000060  6061 6263 6465 6667 6869 6A6B 6C6D 6E6F  `abcdefghijklmno
00000070  7071 7273 7475 7677 7879 7A7B 7C7D 7E7F  pqrstuvwxyz{|}~.

00000080  8081 8283 8485 8687 8889 8A8B 8C8D 8E8F  €‚ƒ„…†‡ˆ‰Š‹ŒŽ
00000090  9091 9293 9495 9697 9899 9A9B 9C9D 9E9F  ‘’“”•–—˜™š›œžŸ
000000A0  A0A1 A2A3 A4A5 A6A7 A8A9 AAAB ACAD AEAF   ¡¢£¤¥¦§¨©ª«¬­®¯
000000B0  B0B1 B2B3 B4B5 B6B7 B8B9 BABB BCBD BEBF  °±²³´µ¶·¸¹º»¼½¾¿

000000C0  C0C1 C2C3 C4C5 C6C7 C8C9 CACB CCCD CECF  ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ
000000D0  D0D1 D2D3 D4D5 D6D7 D8D9 DADB DCDD DEDF  ÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß
000000E0  E0E1 E2E3 E4E5 E6E7 E8E9 EAEB ECED EEEF  àáâãäåæçèéêëìíîï
000000F0  F0F1 F2F3 F4F5 F6F7 F8F9 FAFB FCFD FEFF  ðñòóôõö÷øùúûüýþÿ