简体   繁体   English

C#中的PHP包('N',数字)和二进制连接

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

How do I convert the following code to C#?如何将以下代码转换为 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 .我已经设法转换了 function 的 rest,但我不知道pack('N', number)是如何工作的,也不知道. -operator does when applied to binary variables in PHP. - 运算符在应用于 PHP 中的二进制变量时执行。

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.您使用BitConverter来获取 integer 的byte表示,但您必须翻转它,因为在大多数机器上它是 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.由于我不知道您是将它们打包到MemoryStream还是byte[]中(尽管您应该这样做),所以我将准确地展示这一点。

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[] .然后你可以将它传输到你的缓冲区,对于 C# 可能是一个byte[] Here's how you might do 2 integers:以下是您可以如何处理 2 个整数:

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;

pack('N', $number1) returns the integer $number1 as a 4-byte binary string in big endian byte order. pack('N', $number1) 以大端字节顺序返回 integer $number1 作为 4 字节二进制字符串。

The "."这 ”。” operator concatenates strings.运算符连接字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM