【问题标题】:Converting C# BitConverter.GetBytes() to PHP将 C# BitConverter.GetBytes() 转换为 PHP
【发布时间】:2020-08-04 16:02:36
【问题描述】:

我正在尝试将此 C# 代码移植到 PHP:

var headerList = new List<byte>();

headerList.AddRange(Encoding.ASCII.GetBytes("Hello\n"));
headerList.AddRange(BitConverter.GetBytes(1));

byte[] header = headerList.ToArray();

如果我输出header,它是什么样子的?

我目前的进展:

    $in_raw = "Hello\n";
    
    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);

这给了我这个输出:721011081081111010000000

我非常有信心将字符串转换为 ASCII 字节的第一部分是正确的,但是这些 BitConverter...我不知道输出会是什么...

此字符串(或字节数组)用作套接字连接的握手。我知道 C# 版本确实可以工作,但我的翻新代码不行。

【问题讨论】:

  • 如果有帮助,可以使用在线 C# repl 来检查代码:repl.it/repls/LinedPreviousDistributionsoftware
  • @ChrisHaas 请将其作为正确答案发布(连同实际输出,以及您可能想要添加的任何评论),因为它解决了我的问题。

标签: c# php type-conversion


【解决方案1】:

如果您无法访问可以运行 C# 的机器/工具,则可以使用几个 REPL websites。我已经获取了您的代码,限定了几个命名空间(只是为了方便),将其包装在 main() 方法中,只作为 CLI 和 put it here 运行一次。它还包括一个for 循环,该循环将数组的内容写出,以便您可以查看每个索引处的内容。

这是相同的代码供参考:

using System;

class MainClass {
  public static void Main (string[] args) {
    var headerList = new System.Collections.Generic.List<byte>();

    headerList.AddRange(System.Text.Encoding.ASCII.GetBytes("Hello\n"));
    headerList.AddRange(System.BitConverter.GetBytes(1));

    byte[] header = headerList.ToArray();

    foreach(byte b in header){
      Console.WriteLine(b);
    }
  }
}

当您运行此代码时,会生成以下输出:

72
101
108
108
111
10
1
0
0
0

【讨论】:

    【解决方案2】:

    Encoding.ASCII.GetBytes("Hello\n").ToArray() 给出 byte[6] { 72, 101, 108, 108, 111, 10 }

    BitConverter.GetBytes((Int64)1).ToArray() 给出 byte[8] { 1, 0, 0, 0, 0, 0, 0, 0 }

    BitConverter.GetBytes((Int32)1).ToArray() 字节[4] { 1, 0, 0, 0 }

    最后一个是1的默认编译器转换。

    如果是 PHP 代码,请尝试 $byteK=array(4);和 $i

    【讨论】:

      【解决方案3】:

      字符串 "Hello\n" 已经用 ASCII 编码,所以你无事可做。

      BitConverter.GetBytes() 以机器字节顺序给出 32 位整数的二进制表示,这可以在 PHP 中使用pack() 函数和l 格式完成。

      所以 PHP 代码很简单:

      $in = "Hello\n";
      $in .= pack('l', 1);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-18
        • 2015-01-17
        • 2016-07-02
        • 2011-11-01
        • 2011-01-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多