【问题标题】:How to convert int[] to byte[]如何将 int[] 转换为 byte[]
【发布时间】:2010-11-08 08:01:23
【问题描述】:

我有一个表示 RGB 图像的整数数组,我想将其转换为字节数组并将其保存到文件中。

在 Java 中将整数数组转换为字节数组的最佳方法是什么?

【问题讨论】:

  • 如果您提及您选择将 int[] 转换为 byte[] 的原因,也许您会得到更好、更明确的答案。

标签: java arrays type-conversion


【解决方案1】:

正如Brian 所说,你需要弄清楚你需要什么样的转换。

您要将其保存为“普通”图像文件(jpg、png 等)吗?

如果是这样,您可能应该使用Java Image I/O API。

如果要将其保存为“原始”格式,则必须指定写入字节的顺序,然后使用IntBuffer 和 NIO。

作为使用 ByteBuffer/IntBuffer 组合的示例:

import java.nio.*;
import java.net.*;

class Test
{   
    public static void main(String [] args)
        throws Exception // Just for simplicity!
    {
        int[] data = { 100, 200, 300, 400 };

        ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);        
        IntBuffer intBuffer = byteBuffer.asIntBuffer();
        intBuffer.put(data);

        byte[] array = byteBuffer.array();

        for (int i=0; i < array.length; i++)
        {
            System.out.println(i + ": " + array[i]);
        }
    }
}

【讨论】:

    【解决方案2】:

    也许用这个方法

    byte[] integersToBytes(int[] values)
    {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       DataOutputStream dos = new DataOutputStream(baos);
       for(int i=0; i < values.length; ++i)
       {
            dos.writeInt(values[i]);
       }
    
       return baos.toByteArray();
    }  
    

    【讨论】:

    • 这会将 int 拆分为 byte。我不认为这是需要的。
    • 他想把它保存到一个文件中以备后用,所以这个比较合适
    • 你为什么要把baos包裹在dos里面?
    【解决方案3】:

    您需要先决定如何将 1 个整数转换为一组字节。

    很可能 (?) 1 个整数到 4 个字节,并使用移位(&gt;&gt;&lt;&lt;)运算符来取出每个字节(注意字节顺序!)。复制到整数数组长度4倍的字节数组。

    【讨论】:

      【解决方案4】:

      如果您的意图是保存到文件,您可能希望使用 FileOutputStream.write 直接保存在文件中:

          OutputStream os = new FileOutputStream("aa");
          int[] rgb = { 0xff, 0xff, 0xff };
          for (int c : rgb) {
              os.write(c);
          }
          os.close();
      

      因为它:

      将指定字节写入此输出流。写入的一般约定是将一个字节写入输出流。要写入的字节是参数 b 的 8 个低位。 b 的高 24 位被忽略。

      【讨论】:

        【解决方案5】:

        我创建了这段代码,它运行良好:

            int IntToByte(byte arrayDst[], int arrayOrg[], int maxOrg){
                int i;
                int idxDst;
                int maxDst;
                //
                maxDst = maxOrg*4;
                //
                if (arrayDst==null)
                    return 0;
                if (arrayOrg==null)
                    return 0;
                if (arrayDst.length < maxDst)
                    return 0;
                if (arrayOrg.length < maxOrg)
                    return 0;
                //
                idxDst = 0;
                for (i=0; i<maxOrg; i++){
                    // Copia o int, byte a byte.
                    arrayDst[idxDst] = (byte)(arrayOrg[i]);
                    idxDst++;
                    arrayDst[idxDst] = (byte)(arrayOrg[i] >> 8);
                    idxDst++;
                    arrayDst[idxDst] = (byte)(arrayOrg[i] >> 16);
                    idxDst++;
                    arrayDst[idxDst] = (byte)(arrayOrg[i] >> 24);
                    idxDst++;
                }
                //
                return idxDst;
            }
        
            int ByteToInt(int arrayDst[], byte arrayOrg[], int maxOrg){
                int i;
                int v;
                int idxOrg;
                int maxDst;
                //
                maxDst = maxOrg/4;
                //
                if (arrayDst==null)
                    return 0;
                if (arrayOrg==null)
                    return 0;
                if (arrayDst.length < maxDst)
                    return 0;
                if (arrayOrg.length < maxOrg)
                    return 0;
                //
                idxOrg = 0;
                for (i=0; i<maxDst; i++){
                    arrayDst[i] = 0;
                    //
                    v = 0x000000FF & arrayOrg[idxOrg];
                    arrayDst[i] = arrayDst[i] | v;
                    idxOrg++;
                    //
                    v = 0x000000FF & arrayOrg[idxOrg];
                    arrayDst[i] = arrayDst[i] | (v << 8);
                    idxOrg++;
                    //
                    v = 0x000000FF & arrayOrg[idxOrg];
                    arrayDst[i] = arrayDst[i] | (v << 16);
                    idxOrg++;
                    //
                    v = 0x000000FF & arrayOrg[idxOrg];
                    arrayDst[i] = arrayDst[i] | (v << 24);
                    idxOrg++;
                }
                //
                return maxDst;
            }
        

        【讨论】:

          【解决方案6】:

          我会将“DataOutputStream”与“ByteArrayOutputStream”一起使用。

          public final class Converter {
          
              private static final int BYTES_IN_INT = 4;
          
              private Converter() {}
          
              public static byte [] convert(int [] array) {
                  if (isEmpty(array)) {
                      return new byte[0];
                  }
          
                  return writeInts(array);
              }
          
              public static int [] convert(byte [] array) {
                  if (isEmpty(array)) {
                      return new int[0];
                  }
          
                  return readInts(array);
              }
          
              private static byte [] writeInts(int [] array) {
                  try {
                      ByteArrayOutputStream bos = new ByteArrayOutputStream(array.length * 4);
                      DataOutputStream dos = new DataOutputStream(bos);
                      for (int i = 0; i < array.length; i++) {
                          dos.writeInt(array[i]);
                      }
          
                      return bos.toByteArray();
                  } catch (IOException e) {
                      throw new RuntimeException(e);
                  }
              }
          
              private static int [] readInts(byte [] array) {
                  try {
                      ByteArrayInputStream bis = new ByteArrayInputStream(array);
                      DataInputStream dataInputStream = new DataInputStream(bis);
                      int size = array.length / BYTES_IN_INT;
                      int[] res = new int[size];
                      for (int i = 0; i < size; i++) {
                          res[i] = dataInputStream.readInt();
                      }
                      return res;
                  } catch (IOException e) {
                      throw new RuntimeException(e);
                  }
              }
          }
          
              public class ConverterTest {
          
              @Test
              public void convert() {
                  final int [] array = {-1000000, 24000, -1, 40};
                  byte [] bytes = Converter.convert(array);
                  int [] array2 = Converter.convert(bytes);
          
                  assertTrue(ArrayUtils.equals(array, array2));
          
                  System.out.println(Arrays.toString(array));
                  System.out.println(Arrays.toString(bytes));
                  System.out.println(Arrays.toString(array2));
              }
          }
          

          打印:

          [-1000000, 24000, -1, 40]
          [-1, -16, -67, -64, 0, 0, 93, -64, -1, -1, -1, -1, 0, 0, 0, 40]
          [-1000000, 24000, -1, 40]
          

          【讨论】:

          • 这与此答案几乎完全相同:stackoverflow.com/a/1086071(我看到的唯一区别是您对ByteArrayOutputStream 的初始值)。你能解释一下这个答案是如何增加新信息的吗?
          • 只是重构。
          【解决方案7】:
            /** int[] --> byte[] */
            private byte[] toByte(int[] data) throws IOException {
              
              byte[] bytes = new byte[data.length];
              for (int i = 0; i < bytes.length; i++) {
                bytes[i] = (byte) data[i];
              }
              return bytes;
            }
          

          真的很简单???

          【讨论】:

            猜你喜欢
            • 2012-02-05
            • 1970-01-01
            • 2017-03-18
            • 2019-08-08
            • 2011-06-24
            • 1970-01-01
            • 2020-02-03
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多