Follow this:
The equivalent of string.length
would be strlen($string)
to count the number of characters, to have Unicode compatibility, use:
$j = preg_match_all('/.{1}/us', $string, $data);
The equivalent of bytes.length
would be count($bytes)
to count the number of items in the array
The equivalent of bytes.push(char >>> 8)
would be $bytes[] = $char >> 8;
To concatenate a string to an existing Javascript variable we use +=
, in PHP we use .=
The equivalent of string.charCodeAt
would be ord(substr($string, $i, 1));
, for Unicode compatibility, use:
function unicode_ord($char) {
list (, $ord) = unpack('N', mb_convert_encoding($char, 'UCS-4BE', 'UTF-8'));
return $ord;
}
The equivalent String.fromCharCode(char);
would be chr($char)
, for Unicode compatibility, use:
function unicode_chr($u) {
return mb_convert_encoding('&#' . intval($u) . ';', 'UTF-8', 'HTML-ENTITIES');
}
I believe the code should look like this:
<?php
function unicode_ord($char) {
list (, $ord) = unpack('N', mb_convert_encoding($char, 'UCS-4BE', 'UTF-8'));
return $ord;
}
function unicode_chr($u) {
return mb_convert_encoding('&#' . intval($u) . ';', 'UTF-8', 'HTML-ENTITIES');
}
function bytesToWords($bytes) {
$str = '';
$j = count($bytes);
for($i = 0; $i < $j; $i += 2) {
$char = $bytes[$i] << 8;
if ($bytes[$i + 1]) {
$char |= $bytes[$i + 1];
}
$str .= unicode_chr($char);
}
return $str;
}
function bytesFromWords($string) {
$bytes = array();
$j = preg_match_all('/.{1}/us', $string, $data);
$data = $data[0];
for($i = 0; $i < $j; $i++) {
$char = unicode_ord($data[$i]);
$bytes[] = $char >> 8;
$bytes[] = $char & 0xFF;
}
return $bytes;
}
$data = bytesFromWords('㬁愃膘ƘჀ䚐⦀飠噋&ӡ㏃棱쌌ص䌠');
echo implode(', ', $data);
echo bytesToWords($data);
Extra
In the Javascript version you used str.replace('undefined', '');
why the variable was not defined, but it is best to set a value to variable and so you will not need replace, so:
function bytesToWords(bytes) {
var str = "";//Setado string vazia
for(var i = 0; i < bytes.length; i += 2) {
var char = bytes[i] << 8;
if (bytes[i + 1])
char |= bytes[i + 1];
str += String.fromCharCode(char);
}
return str;
}
aeee, thank you very much, you have done much more than help me!! I will give you all the positive things possible to me ;D
– Vinícius Lara
@user3163662 it is enough to participate in the community collaborating with answers and asking that is already well enough hehehe :) Note that I answered in Soen also http://stackoverflow.com/a/29786119/1518921 if it makes sense to you, accept there, grateful!
– Guilherme Nascimento
I accepted there, if I can do the honors: http://stackoverflow.com/questions/29782588/how-transcribe-bytestohex-for-php/29782930#29782930
– Vinícius Lara
I expressed myself badly, I meant "pass" to answer if I can :p
– Vinícius Lara
A yes when I can I pass there :) ... Good night!
– Guilherme Nascimento
Relax haha Good afternoon
– Vinícius Lara