0

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.

the.salman.a
  • 945
  • 8
  • 29
  • https://stackoverflow.com/questions/885597/string-to-byte-array-in-php – Alive to die - Anant Mar 20 '18 at 11:18
  • 4
    `"\x02"` is a *PHP string literal notation* which expresses the byte `02`. `"\x"` doesn't mean anything in particular, and concatenating it with `"02"` just results in the string `"\x02"`; strings' values aren't recursively interpreted at any time to resolve possible meanings that mean something in string literal notation. I.e. it would be pretty surprising behaviour if `$userinput1 . $userinput2` would be interpreted and result in the byte `02` because it happens to form the value "\x02". – deceze Mar 20 '18 at 11:24
  • I don't understand the reason of this unuseful and long reply, when vuryss user has replied in a very useful way. Sorry, but your reply doesn't help anyone. – Stevenworks Pictures Mar 21 '18 at 11:07

1 Answers1

3

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

Like that:

$codes = ["02", "66", "6c", "6a", "3a", "03"];
$byteString1 = hex2bin(implode('', $codes));
vuryss
  • 1,270
  • 8
  • 16