【问题标题】:Java integer to byte arrayJava整数到字节数组
【发布时间】:2018-03-08 09:38:36
【问题描述】:

我得到一个整数:1695609641

当我使用方法时:

String hex = Integer.toHexString(1695609641);
system.out.println(hex); 

给予:

6510f329

但我想要一个字节数组:

byte[] bytearray = new byte[] { (byte) 0x65, (byte)0x10, (byte)0xf3, (byte)0x29};

我该怎么做?

【问题讨论】:

标签: java arrays integer byte


【解决方案1】:

使用Java NIO的ByteBuffer很简单:

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

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

输出:

0x65 0x10 0xf3 0x29

【讨论】:

  • 如果您总是想要两个十六进制字符以及大写十六进制,则使用格式"0x%02X",例如System.out.format("0x%02X", (byte) 10) 显示 0x0A
  • @conor Javadoc 说 allocateDirect() 确实有成本,应该在缓冲区保留一段时间时使用。虽然答案有效,但对于手头的用例来说似乎有点矫枉过正。
  • 您可以使用 Integer.SIZE/8 来避免对 4 进行硬编码,这种模式适用于 Long 等其他类型。
  • @davenpcj 你甚至可以使用 Integer.SIZE / Byte.SIZE
  • @rkosegi 甚至是从 Java 8 开始的 Integer.BYTES :)
【解决方案2】:

怎么样:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

这个想法不是我的。我是从some post on dzone.com 获取的。

【讨论】:

  • 我明白你的意思,但是对于这个特定的任务,“我的”代码比一些“神奇”的 ByteBuffer 更具声明性和清晰性,人们必须检查它才能看到它的作用。
  • @Kevin - 这非常苛刻 - 在很多情况下这种代码是合适的,例如在图像处理中。 JDK 库总的来说很棒,但它们没有涵盖和/或没有针对所有用例进行优化。
  • 同意;与一些简单且众所周知的字节操作相比,ByteBuffer 的开销和复杂性可能并不合适。
  • 我要补充的另一点是,您使用了无符号右移运算符>>>,而不是右移运算符>> (docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html),因此行为可能不如预期/正如预期的有符号数和无符号数
  • 这种方法似乎比提到的 ByteBuffer 或 BigInteger 方法快一点。如果您要进行大量转化,还需要考虑其他因素。
【解决方案3】:

BigInteger.valueOf(1695609641).toByteArray()

【讨论】:

  • 你有什么保证会产生一个 4 字节的数组?
  • 正是 MeBigFatGuy 写的。 BigInteger.toByteArray() 的 Javadoc 声明:“该数组将包含表示此 BigInteger 所需的最小字节数......”
  • 它在问题的什么地方要求字节数组的长度为 4?根据算法,这意味着您可以利用数组的长度
  • 这更加动态,应该是正确的答案。如果您愿意,您可以简单地执行 Array append 来创建所需的大小。特别是当您必须考虑 Java 签名的 int 值时。
  • 这似乎为 0x7f 创建了一个字节,为 0x80 创建了两个字节(这两个字节为: 0x0 0x80 )。
【解决方案4】:
byte[] IntToByteArray( int data ) {    
    byte[] result = new byte[4];
    result[0] = (byte) ((data & 0xFF000000) >> 24);
    result[1] = (byte) ((data & 0x00FF0000) >> 16);
    result[2] = (byte) ((data & 0x0000FF00) >> 8);
    result[3] = (byte) ((data & 0x000000FF) >> 0);
    return result;        
}

【讨论】:

    【解决方案5】:

    使用Guava

    byte[] bytearray = Ints.toByteArray(1695609641);
    

    【讨论】:

      【解决方案6】:
      byte[] conv = new byte[4];
      conv[3] = (byte) input & 0xff;
      input >>= 8;
      conv[2] = (byte) input & 0xff;
      input >>= 8;
      conv[1] = (byte) input & 0xff;
      input >>= 8;
      conv[0] = (byte) input;
      

      【讨论】:

      【解决方案7】:
      public static byte[] intToBytes(int x) throws IOException {
          ByteArrayOutputStream bos = new ByteArrayOutputStream();
          DataOutputStream out = new DataOutputStream(bos);
          out.writeInt(x);
          out.close();
          byte[] int_bytes = bos.toByteArray();
          bos.close();
          return int_bytes;
      }
      

      【讨论】:

        【解决方案8】:

        下面的块至少可以用于通过 UDP 发送 int。

        int 到字节数组:

        public byte[] intToBytes(int my_int) throws IOException {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutput out = new ObjectOutputStream(bos);
            out.writeInt(my_int);
            out.close();
            byte[] int_bytes = bos.toByteArray();
            bos.close();
            return int_bytes;
        }
        

        字节数组到int:

        public int bytesToInt(byte[] int_bytes) throws IOException {
            ByteArrayInputStream bis = new ByteArrayInputStream(int_bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            int my_int = ois.readInt();
            ois.close();
            return my_int;
        }
        

        【讨论】:

        • ObjectOutputStream 的使用不正确。使用DataOutputStream,使用OOS使得字节数组不是4字节。
        【解决方案9】:

        因为通常您希望稍后将此数组转换回 int,所以以下是将 int 数组转换为字节数组的方法,反之亦然:

        public static byte[] convertToByteArray(final int[] pIntArray)
        {
            final byte[] array = new byte[pIntArray.length * 4];
            for (int j = 0; j < pIntArray.length; j++)
            {
                final int c = pIntArray[j];
                array[j * 4] = (byte)((c & 0xFF000000) >> 24);
                array[j * 4 + 1] = (byte)((c & 0xFF0000) >> 16);
                array[j * 4 + 2] = (byte)((c & 0xFF00) >> 8);
                array[j * 4 + 3] = (byte)(c & 0xFF);
            }
            return array;
        }
        
        public static int[] convertToIntArray(final byte[] pByteArray)
        {
            final int[] array = new int[pByteArray.length / 4];
            for (int i = 0; i < array.length; i++)
                array[i] = (((int)(pByteArray[i * 4]) << 24) & 0xFF000000) |
                        (((int)(pByteArray[i * 4 + 1]) << 16) & 0xFF0000) |
                        (((int)(pByteArray[i * 4 + 2]) << 8) & 0xFF00) |
                        ((int)(pByteArray[i * 4 + 3]) & 0xFF);
            return array;
        }
        

        请注意,由于符号传播等原因,在转换回 int 时需要“& 0xFF...”。

        【讨论】:

          【解决方案10】:

          如果您使用的是apache-commons

          public static byte[] toByteArray(int value) {
              byte result[] = new byte[4];
              return Conversion.intToByteArray(value, 0, result, 0, 4);
          }
          

          【讨论】:

            【解决方案11】:
            integer & 0xFF
            

            第一个字节

            (integer >> 8) & 0xFF
            

            对于第二个和循环等,写入预分配的字节数组。有点乱,很遗憾。

            【讨论】:

              【解决方案12】:

              org.apache.hadoop.hbase.util.Bytes 类有很多方便的 byte[] 转换方法,但您可能不想为了这个目的而将整个 HBase jar 添加到您的项目中。令人惊讶的是,这种方法不仅缺少 JDK 中的 AFAIK,而且还缺少像 commons io 这样的明显库。

              【讨论】:

                【解决方案13】:

                我的尝试:

                public static byte[] toBytes(final int intVal, final int... intArray) {
                    if (intArray == null || (intArray.length == 0)) {
                        return ByteBuffer.allocate(4).putInt(intVal).array();
                    } else {
                        final ByteBuffer bb = ByteBuffer.allocate(4 + (intArray.length * 4)).putInt(intVal);
                        for (final int val : intArray) {
                            bb.putInt(val);
                        }
                        return bb.array();
                    }
                }
                

                有了它,你可以做到:

                byte[] fourBytes = toBytes(0x01020304);
                byte[] eightBytes = toBytes(0x01020304, 0x05060708);
                

                完整类在这里:https://gist.github.com/superbob/6548493,它支持从短裤或长期初始化

                byte[] eightBytesAgain = toBytes(0x0102030405060708L);
                

                【讨论】:

                  猜你喜欢
                  • 2012-07-10
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-10-04
                  • 1970-01-01
                  • 2011-05-29
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多