Hướng dẫn ascii to binary php

Strings in PHP are always BLOBs. So you can use a string to hold the value for your database BLOB. All of this stuff base-converting and so on has to do with presenting that BLOB.

If you want a nice human-readable representation of your BLOB then it makes sense to show the bytes it contains, and probably to use hex rather than decimal. Hence, the string "41 42 43" is a good way to present the byte array that in C# would be

var bytes = new byte[] { 0x41, 0x42, 0x43 };

but it is obviously not a good way to represent those bytes! The string "ABC" is an efficient representation, because it is in fact the same BLOB (only it's not so Large in this case).

In practice you will typically get your BLOBs from functions that return string - such as that hashing function, or other built-in functions like fread.

In the rare cases (but not so rare when just trying things out/prototyping) that you need to just construct a string from some hard-coded bytes I don't know of anything more efficient than converting a "hex string" to what is often called a "binary string" in PHP:

$myBytes = "414243";
$data = pack('H*', $myBytes);

If you var_dump($data); it'll show you string(3) "ABC". That's because 0x41 = 65 decimal = 'A' (in basically all encodings).

Since looking at binary data by interpreting it as a string is not exactly intuitive, you may want to make a basic wrapper to make debugging easier. One possible such wrapper is

class blob
{
    function __construct($hexStr = '')
    {
        $this->appendHex($hexStr);
    }

    public $value;

    public function appendHex($hexStr)
    {
        $this->value .= pack('H*', $hexStr);
    }

    public function getByte($index)
    {
        return unpack('C', $this->value{$index})[1];
    }

    public function setByte($index, $value)
    {
        $this->value{$index} = pack('C', $value);
    }

    public function toArray()
    {
        return unpack('C*', $this->value);
    }
}

This is something I cooked up on the fly, and probably just a starting point for your own wrapper. But the idea is to use a string for storage since this is the most efficient structure available in PHP, while providing methods like toArray() for use in debugger watches/evaluations when you want to examine the contents.

Of course you may use a perfectly straightforward PHP array instead and pack it to a string when interfacing with something that uses strings for binary data. Depending on the degree to which you are actually going to modify the blob this may prove easier, and although it isn't space efficient I think you'd get acceptable performance for many tasks.

An example to illustrate the functionality:

// Construct a blob with 3 bytes: 0x41 0x42 0x43.
$b = new blob("414243");

// Append 3 more bytes: 0x44 0x45 0x46.
$b->appendHex("444546");

// Change the second byte to 0x41 (so we now have 0x41 0x41 0x43 0x44 0x45 0x46).
$b->setByte(1, 0x41); // or, equivalently, setByte(1, 65)

// Dump the first byte.
var_dump($b->getByte(0));

// Verify the result. The string "AACDEF", because it's only ASCII characters, will have the same binary representation in basically any encoding.
$ok = $b->value == "AACDEF";

In this example we are going to convert string to binary and binary to string with PHP.

function strigToBinary($string)
{
$characters = str_split($string);

$binary = [];
foreach ($characters as $character) {
$data = unpack('H*', $character);
$binary[] = base_convert($data[1], 16, 2);
}

return implode(' ', $binary);
}

function binaryToString($binary)
{
$binaries = explode(' ', $binary);

$string = null;
foreach ($binaries as $binary) {
$string .= pack('H*', dechex(bindec($binary)));
}

return $string;
}

$string = 'inanzzz';
echo 'STRING: '.$string.PHP_EOL;
echo 'BINARY: '.$binary = strigToBinary($string).PHP_EOL;
echo 'STRING: '.binaryToString($binary).PHP_EOL;
STRING: inanzzz
BINARY: 1101001 1101110 1100001 1101110 1111010 1111010 1111010
STRING: inanzzz

Hướng dẫn ascii to binary php

Tool online: Convert string to binary online

The PHP’s core offers some function to convert data between binary, decimal, hexadecimal and etc. But how to convert from binary string to binary, we offer some function to do that.

Method 1: using functions unpack and base_convert

function strToBin($input)
    {
        if (!is_string($input))
            return false;
        $value = unpack('H*', $input);
        return base_convert($value[1], 16, 2);
    }

Example:

echo(strToBin('tuto')); //1110100011101010111010001101111

but with the long string, we can’t convert

echo(strToBin('tutorialspots.com')); //0000000000000000000000000000000000000000000000000000000000000000

Because of the function base_convert can’t work with the big number. The limitation is:

echo(PHP_INT_MAX);//2147483647

What’s the sulution? we can split the hexadecimal string into chunks, convert each chunk and join chunk. We must change the above function:

function strToBin3($input)
{
    if (!is_string($input))
        return false;
    $input = unpack('H*', $input);
    $chunks = str_split($input[1], 2);
    $ret = '';
    foreach ($chunks as $chunk)
    {
        $temp = base_convert($chunk, 16, 2);
        $ret .= str_repeat("0", 8 - strlen($temp)) . $temp;
    }
    return $ret;
}

Example:

echo(strToBin('tutorialspots.com')); //0111010001110101011101000110111101110010011010010110000101101100011100110111000001101111011101000111001100101110011000110110111101101101

Method 2: use function decbin and ord to convert

function strToBin($input)
{
    if (!is_string($input))
        return false;
    $ret = '';
    for ($i = 0; $i < strlen($input); $i++)
    {
        $temp = decbin(ord($input{$i}));
        $ret .= str_repeat("0", 8 - strlen($temp)) . $temp;
    }
    return $ret;
}

Example:

echo (strToBin('phptuts')); //01110000011010000111000001110100011101010111010001110011

Method 3:

Use GMP module

function string_to_bin($string){
        $a = unpack('C*', $string);
        $c = count($a);
        $ret = gmp_init(0);
        foreach($a as $i=>$num){
            $ret = gmp_add($ret,gmp_mul($num,gmp_pow(256,$c-$i)));
        }
        $ret = gmp_strval($ret,2);
         
        return str_repeat("0", strlen($string)*8 - strlen($ret)) .$ret;
    }