Stevenworks Pictures
Stevenworks Pictures

Reputation: 125

PHP - Create a valid byte string

INTRO

I have two strings of bytes. The first one is created starting from an array of hex codes and using a for cicle to create the byte string:

$codes = ["02", "66", "6c", "6a", "3a", "03"];
$bytestring1 = "";
for ($i = 0; $i < count($codes); $i++) $byteString1 .= "\x" . $codes[$i];

The second string is created writing it directly by hand:

$bytestring2 = "\x02\x66\x6c\x6a\x3a\x03";

WHAT I EXPECT

I expect that $bytestring1 and $bytestring2 are identical.

WHAT HAPPENS

When I send $bytestring1 and $bytestring2 to a client using socket_send command, the variable $bytestring1 appears to be a pure string and it doesn't work.

The variable $bytestring2, instead, is recognized as a string of bytes and it works.

QUESTION

How can I create a valid string of bytes using the first method?

Thanx.

Upvotes: 1

Views: 3990

Answers (1)

vuryss
vuryss

Reputation: 1300

Use http://php.net/manual/en/function.hex2bin.php

Like that:

$codes = ["02", "66", "6c", "6a", "3a", "03"];
$byteString1 = hex2bin(implode('', $codes));

Upvotes: 4

Related Questions