I’m trying to port this C# code to PHP:
var headerList = new List<byte>();
headerList.AddRange(Encoding.ASCII.GetBytes("Hellon"));
headerList.AddRange(BitConverter.GetBytes(1));
byte[] header = headerList.ToArray();
If I output header
, what does it looks like?
My progress so far:
$in_raw = "Hellon";
for($i = 0; $i < mb_strlen($in_raw, 'ASCII'); $i++){
$in.= ord($in_raw[$i]);
}
$k=1;
$byteK=array(8); // should be 16? 32?...
for ($i = 0; $i < 8; $i++){
$byteK[$i] = (( $k >> (8 * $i)) & 0xFF); // Don't known if it is a valid PHP bitwise op
}
$in.=implode($byteK);
print_r($in);
Which gives me this output: 721011081081111010000000
I’m pretty confident that the first part of converting the string to ASCII bytes is correct, but these BitConverter… I don’t know what to expect as output…
This string (or byte array) is used as an handshake for an socket connection. I know that the C# version does work, but my refurnished code doesn’t.
3
Answers
Encoding.ASCII.GetBytes(“Hellon”).ToArray()
gives byte[6] { 72, 101, 108, 108, 111, 10 }
BitConverter.GetBytes((Int64)1).ToArray()
gives byte[8] { 1, 0, 0, 0, 0, 0, 0, 0 }
BitConverter.GetBytes((Int32)1).ToArray()
byte[4] { 1, 0, 0, 0 }
the last one is default compiler conversion of 1.
if PHP code please try $byteK=array(4); and $i < 4
The string “Hellon” is already encoded in ASCII so you have nothing to do.
BitConverter.GetBytes()
gives the binary representation of a 32-bit integer in machine byte order, which can be done in PHP with thepack()
function and thel
format.So the PHP code is simply:
If you don’t have access to a machine/tool that can run C#, there are a couple of REPL websites that you can use. I’ve taken your code, qualified a couple of the namespaces (just for convenience), wrapped it in a
main()
method to just run once as a CLI and put it here. It also includes afor
loop that writes the contents of the array out so that you can see what is at each index.Here’s the same code for reference:
When you run this code, the following output is generated: