1

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.

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

pack('N', $number1) returns the integer $number1 as a 4-byte binary string in big endian byte order.

The "." operator concatenates strings.

1 Comment

How do I get a "4-byte vinary string in big endian byte order" from an integer in C# then?

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.