【问题标题】:Java - Convert byte[] to int[] rgbJava - 将 byte[] 转换为 int[] rgb
【发布时间】:2014-05-04 08:32:01
【问题描述】:

我有一个使用 RobotPeer.getRGBPixels() 获得的 int 数组。我将其转换为字节数组以通过套接字发送它:

 public static byte[] toByteArray(int[] ints){
    byte[] bytes = new byte[ints.length * 4];
            for (int i = 0; i < ints.length; i++) {
        bytes[i * 4] = (byte) (ints[i] & 0xFF);
        bytes[i * 4 + 1] = (byte) ((ints[i] & 0xFF00) >> 8);
        bytes[i * 4 + 2] = (byte) ((ints[i] & 0xFF0000) >> 16);
        bytes[i * 4 + 3] = (byte) ((ints[i] & 0xFF000000) >> 24);
    }
    return bytes;
}

问题是: 我用这个方法:

public static int[] toIntArray(byte buf[]) {
    int intArr[] = new int[buf.length / 4];
    int offset = 0;
    for (int i = 0; i < intArr.length; i++) {
        intArr[i] = (buf[3 + offset] & 0xFF) | ((buf[2 + offset] & 0xFF) << 8)
                | ((buf[1 + offset] & 0xFF) << 16) | ((buf[0 + offset] & 0xFF) << 24);
        offset += 4;
    }
    return intArr;
}

返回 int 数组。然后我从中创建 BufferedImage 并得到: https://www.dropbox.com/s/p754u3tnivigu70/test.jpeg

请帮我解决这个问题。

【问题讨论】:

  • 您的字节顺序错误。 Byte Array and Int conversion in Java 的可能重复项
  • 使用ByteBuffers;他们将为您管理位处理,您可以指定要使用的字节序
  • @BrianRoach 谢谢,我解决了。抱歉创建了重复的问题,下次我会尝试找出答案。

标签: java arrays converter


【解决方案1】:

不用担心位移等; Java 有 ByteBuffer 可以为您处理这些问题,以及启动的字节序:

public static int[] toIntArray(byte buf[]) 
{
    final ByteBuffer buffer = ByteBuffer.wrap(buf)
        .order(ByteOrder.LITTLE_ENDIAN);
    final int[] ret = new int[buf.length / 4];
    buffer.asIntBuffer().put(ret);
    return ret;
}

同样,反过来:

public static byte[] toByteArray(int[] ints)
{
    final ByteBuffer buf = ByteBuffer.allocate(ints.length * 4)
        .order(ByteOrder.LITTLE_ENDIAN);
    buf.asIntBuffer().put(ints);
    return buf.array();
}

不要忘记在您的情况下指定字节序,因为默认情况下ByteBuffers 是大字节序。

【讨论】:

  • 感谢支持,但您的 toIntArray 方法抛出 java.lang.UnsupportedOperationException。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-24
  • 1970-01-01
  • 2012-02-05
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 2016-08-16
相关资源
最近更新 更多