【问题标题】:Java Byte Operation - Converting 3 Byte To Integer DataJava 字节操作 - 将 3 字节转换为整数数据
【发布时间】:2016-01-10 18:14:43
【问题描述】:

我有一些字节整数操作。但我无法弄清楚问题所在。

首先我有一个十六进制数据,我将它保存为一个整数

public static final int hexData = 0xDFC10A;

我正在使用这个函数将它转换为字节数组:

public static byte[] hexToByteArray(int hexNum)
    {
        ArrayList<Byte> byteBuffer = new ArrayList<>();

        while (true)
        {
            byteBuffer.add(0, (byte) (hexNum % 256));
            hexNum = hexNum / 256;
            if (hexNum == 0) break;
        }

        byte[] data = new byte[byteBuffer.size()];
        for (int i=0;i<byteBuffer.size();i++){
            data[i] = byteBuffer.get(i).byteValue();
        }


        return data;
    }

我想再次将 3 字节数组转换为整数,我该怎么做? 或者您也可以建议其他转换函数,例如 hex-to-3-bytes-array 和 3-bytes-to-int 再次感谢您。

更新

在c#中有人使用下面的函数但在java中不起作用

 public static int byte3ToInt(byte[] byte3){
        int res = 0;
        for (int i = 0; i < 3; i++)
        {
            res += res * 0xFF + byte3[i];
            if (byte3[i] < 0x7F)
            {
                break;
            }
        }
        return res;
    }

【问题讨论】:

  • 英语可能不是您的母语。请不要说“我希望你帮助我”,除非你是真心的。这听起来粗鲁和傲慢。让你下次知道!
  • 谢谢指正,我不是这个意思。我会尽量不再使用@NiklasR

标签: java int hex bytearray


【解决方案1】:

这将为您提供价值:

(byte3[0] & 0xff) << 16 | (byte3[1] & 0xff) << 8 | (byte3[2] & 0xff)

这假设字节数组是 3 个字节长。如果您还需要转换较短的数组,您可以使用循环。

另一个方向的转换(int 到 bytes)可以写成这样的逻辑操作:

byte3[0] = (byte)(hexData >> 16);
byte3[1] = (byte)(hexData >> 8);
byte3[2] = (byte)(hexData);

【讨论】:

  • 对于上面的例子,我已经尝试过,对于 14663946 int 值,返回 704991
  • 对了,hexToByteArray方法返回字节的顺序相反;见编辑。
  • 我可以问你一件事,你能回顾一下我的第一个函数,你能像这样优化吗?
  • 再次感谢您!
【解决方案2】:

你可以使用 Java NIO 的 ByteBuffer:

byte[] bytes = ByteBuffer.allocate(4).putInt(hexNum).array();

反之亦然。看看this

举个例子:

final byte[] array = new byte[] { 0x00, (byte) 0xdf, (byte) 0xc1, 0x0a };//you need 4 bytes to get an integer (padding with a 0 byte)
final int x = ByteBuffer.wrap(array).getInt();
// x contains the int 0x00dfc10a

如果你想做类似 C# 代码:

public static int byte3ToInt(final byte[] byte3) {
        int res = 0;
        for (int i = 0; i < 3; i++)
        {
        res *= 256;
        if (byte3[i] < 0)
        {
            res += 256 + byte3[i]; //signed to unsigned conversion
        } else
        {
            res += byte3[i];
        }
        }
        return res;
    }

【讨论】:

  • 需要是 3 字节而不是 4
  • 3 个字节不足以容纳一个 int,你打算如何处理多余的字节?
  • 此外,我可以将其更改为 3 字节,我需要将其更改回 int,我将只使用那种数据 0xDA10AB、0xDFC10A..etc ..
  • @mismanc 给你。如果您计划在未来使用 byte3ToInt,您可能需要添加一些测试。类似于检查它是否真的是一个 3 字节数组。
【解决方案3】:

将整数转换为十六进制:integer.toHexString()

将十六进制字符串转换为整数:Integer.parseInt("FF", 16);

【讨论】:

  • 他想要一个字节[]而不是字符串。
  • @Burkhard sting.getBytes()。或者查看方法的内部实现总是有用的。应该是他最优化的
  • 你是对的,我同意你的观点,但有时你只需要这样做:p
猜你喜欢
  • 2010-12-28
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
  • 2018-11-19
相关资源
最近更新 更多