1

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.

3
  • stackoverflow.com/questions/885597/string-to-byte-array-in-php Commented Mar 20, 2018 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". Commented Mar 20, 2018 at 11:24
  • 1
    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. Commented Mar 21, 2018 at 11:07

1 Answer 1

4

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

Like that:

$codes = ["02", "66", "6c", "6a", "3a", "03"];
$byteString1 = hex2bin(implode('', $codes));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.