【问题标题】:PHP - Java read int8 from StringPHP - Java 从字符串中读取 int8
【发布时间】:2012-09-09 22:52:30
【问题描述】:

我如何将这个 PHP 代码翻译成 Java 代码?

protected function readInt24()
{
    $ret = 0;
    if (strlen($this->_input) >= 3)
    {
        $ret  = ord(substr($this->_input, 0, 1)) << 16;
        $ret |= ord(substr($this->_input, 1, 1)) << 8;
        $ret |= ord(substr($this->_input, 2, 1)) << 0;
        $this->_input = substr($this->_input, 3);
    }
    return $ret;
}

$input 是一个非常疯狂的字符串,它包含 utf 字符(afaik):大约 8�

【问题讨论】:

  • 结果应该是一个整数。
  • 你有什么问题?

标签: java php string numbers int


【解决方案1】:

3 ord(substr($this-&gt;_input, ..., ...)) 检索字符串前三个字符的 ASCII 值。对于每一个,都有一个左移,然后用返回进行或运算。

这在 Java 中会翻译为:

public static int readInt24(String input) {
int ret = 0;
if (input.length() >= 3) {
    ret = input.charAt(0) << 16;
    ret |= input.charAt(1) << 8;
    ret |= input.charAt(2) << 0;
}
return ret;
}

请注意,PHP 代码会将实例变量 _input 截断为仅 3 个字符长。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多