c# - 按位移位 - 在 C# 中获得与在 php 中不同的结果

标签 c# php bit-manipulation

我正在尝试将一些 PHP 转换为 C#,但按位函数给出了不同的结果。

PHP 将返回 248

protected function readInt8()
{
    $ret = 0;
    if (strlen($this->_input) >= 1)
    {
        $sbstr = substr($this->_input, 0, 1);
        $ret = ord($sbstr);
        $this->_input = substr($this->_input, 1);
    }
    return $ret;
}

C# 将返回 63

private int ReadInt8()
{
    int ret = 0;
    if (input.Length >= 1)
    {
        string substr = input.Substring(0, 1);
        ASCIIEncoding ascii = new ASCIIEncoding();
        byte[] buffer = ascii.GetBytes(substr);
        ret = buffer[0]; // 63

        this.input = this.input.Substring(1);
    }

    return ret;
}

否则返回14337

private int ReadInt8()
{
    int ret = 0;

    if (input.Length >= 1)
    {
        string substr = input.Substring(0, 1);

        ret = (int)(substr[0]); // 14337
        this.input = this.input.Substring(1);
    }

    return ret;
}

other question这里适用于较大的值,但不适用于较小的值。我想知道问题是什么。

对不起。昨天有点晚了。

bytes from the server

用下面的函数转换的输入=“??”;

public string GetString(byte[] bytes)
{
    char[] chars = new char[bytes.Length / sizeof(char)];
    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
    return new string(chars);
}

关于转变。我认为它可能需要一个转变,因为 ReadInt16() 需要它。

private int ReadInt16()
{
    int ret = 0;
    if (input.Length >= 2)
    {
        ret  = ((int)(this.input.Substring(0, 1)[0]) & 0xffff) >> 8;
        ret |= ((int)(this.input.Substring(1, 1)[0]) & 0x0000) >> 0;
        this.input = input.Substring(2);
    }
    return ret;
 }

我应该说。我可能误解了 PHP 中该函数的使用。

最佳答案

不要将字符串视为等同于字节数组。字符编码会干扰和破坏数据(如果它实际上不是文本)。如果必须以文本形式传输原始数据,则必须对其进行适当的编码/解码,例如使用 base64 编码。

关于c# - 按位移位 - 在 C# 中获得与在 php 中不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12485416/

相关文章:

c++ - 有什么方法可以加快这个位列表代码的速度吗?

c# - 使用 MsBuild 4.0 编译的程序集是否与只有 .NET 3.5 的计算机兼容?

c# - 如何用C#从FTPS下载文件

PHP preg_replace 模式似乎只有在错误的情况下才有效?

php - Chrooted PHP-FPM脚本过一会儿无法解析DNS

java - 用于补充不包括前导零二进制位的整数值的更好算法

c# - 从 SOAP 请求中读取 XML 属性到 WCF 服务

c# - P/Invoke 有时会导致 Win32 1008 Error with StringBuilder parameters

php - 在 WooCommerce 快速订单预览中显示自定义字段

c - 如何在C中一次清除多个位?