首页 > 解决方案 > 将 C# BitConverter.GetBytes() 转换为 PHP

问题描述

我正在尝试将此 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#phptype-conversion

解决方案


如果您无法访问可以运行 C# 的机器/工具,那么您可以使用几个REPL 网站。我已经获取了您的代码,限定了几个命名空间(只是为了方便),将其包装在一个main()方法中,只作为 CLI 运行一次并将其放在这里。它还包括一个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

推荐阅读