Search code examples
c#phpbinarypack

PHP's pack('N', number) and binary concatenation in C#


How do I convert the following code to C#?

return pack('N', $number1) . pack('N', $number2);

I've managed to convert the rest of the function, but I have no idea how the pack('N', number) works, nor do I know what the .-operator does when applied to binary variables in PHP.


Solution

  • You use BitConverter to get the byte representation of the integer, but than you have to flip it because on most machines it is little-endian. Since I don't know whether you're packing these into a MemoryStream or byte[] (though you should), I'll just show exactly that.

    int myInt = 1234;
    byte[] num1 = BitConverter.GetBytes( myInt );
    if ( BitConverter.IsLittleEndian ) {
        Array.Reverse( num1 );
    }
    

    And then you can transfer that to your buffer, which for C# might be a byte[]. Here's how you might do 2 integers:

    int myInt1 = 1234;
    int myInt2 = 5678;
    byte[] temp1 = BitConverter.GetBytes( myInt1 );
    byte[] temp2 = BitConverter.GetBytes( myInt2 );
    
    if ( BitConverter.IsLittleEndian ) {
        Array.Reverse( temp1 );
        Array.Reverse( temp2 );
    }
    
    byte[] buffer = new byte[ temp1.Length + temp2.Length ];
    Array.Copy( temp1, 0, buffer, 0, temp1.Length );
    Array.Copy( temp2, 0, buffer, temp1.Length, temp2.Length );
    return buffer;