【问题标题】:XXHash - Java vs. PHPXXHash——Java 与 PHP
【发布时间】:2022-12-15 09:12:05
【问题描述】:

在 PHP 和 Java 中使用 XXHash 库时,我每次都会得到不同的结果(此实现:https://github.com/OpenHFT/Zero-Allocation-Hashing)。

爪哇

Log.e('xx128low', Long.toHexString(LongHashFunction.xx128low().hashChars("12345")));
Log.e('xx', Long.toHexString(LongHashFunction.xx().hashChars("12345")));
Log.e('xx3', Long.toHexString(LongHashFunction.xx3().hashChars("12345")));

结果:

E/xx128low: ee40efb40996b83a
E/xx: 807d4a5b54b8db4
E/xx3: 3a4df7c76c99039

PHP

var_dump(hash('xxh128', (string)12345));
var_dump(hash('xxh64', (string)12345));
var_dump(hash('xxh3', (string)12345));

结果:

string(32) "4af3da69f61e14cf26f4c14b6b6bfdb4"
string(16) "c6f2d2dd0ad64fb6"
string(16) "f34099ede96b5581"

我无法发现问题。任何人都可以帮助我吗?

【问题讨论】:

  • 我要说的是 Java 端给出了不正确的值,因为 PHP 和 Python 散列值一致。
  • @Sammitch 好点,没检查...
  • 还值得注意的是,PHP 算法分别是 xxh3_128、xxh_64 和 xxh3_64,我无法弄清楚 xx128low 在 Java 代码中应该是什么。也许是 128 位哈希的“低”一半?

标签: java php


【解决方案1】:

hash('xxh3', (string)12345) 的 java 变体如下

public static String hexToString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();

        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        return hexString.toString();
    }

    public static byte[] longToBytesArray(long x) {
        ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
        buffer.putLong(x);
        return buffer.array();
    }


    public static String hashingXxh3() throws IOException {
        long hashing = LongHashFunction.xx3().hashBytes("12345".getBytes(StandardCharsets.UTF_8));
        String toHexStr = hexToString(longToBytesArray(hashing));

        return toHexStr;
    }

enter image description here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2022-01-14
    • 2011-01-01
    • 2013-01-28
    • 2011-07-27
    • 1970-01-01
    相关资源
    最近更新 更多