gpt4 book ai didi

java - 将 int 0-65535 存储在固定 16 位上并转换回来

转载 作者:行者123 更新时间:2023-12-02 09:21:35 24 4
gpt4 key购买 nike

我有 int 数字,其值在 0-65535 之间。我需要将每个数字存储为 2 个字节长度的 byte 数组,无论该数字是否也适合 1 个字节。一旦数字存储在字节数组中,我就需要能够将它们转换回 int 。现在我不知道如何在 2 个字节上存储不在 -32,768 和 32,767 之间的数字,并能够正确地将其转换回其原始 int 值。

最佳答案

您可以将 0-65535 的值存储在 char 值中,并将 char 转换为 byte[](长度为2)使用以下方法:

    public static byte[] toBytes(char c) {
return ByteBuffer.allocate(Character.BYTES).putChar(c).array();
}

参见here

编辑:

使用ByteBuffer向后工作:

    public static char charFromBytes(byte[] bytes) {
return ByteBuffer.wrap(bytes).getChar();
}

关于java - 将 int 0-65535 存储在固定 16 位上并转换回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58660568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com