【问题标题】:How to convert a byte array to two long values?如何将一个字节数组转换为两个长值?
【发布时间】:2011-01-22 00:19:03
【问题描述】:

我正在使用rs.getBytes("id") 从 JDBC ResultSet 读取一个 16 字节数组 (byte[16]),现在我需要将它转换为两个长值。我该怎么做?

这是我尝试过的代码,但我可能没有正确使用ByteBuffer

byte[] bytes = rs.getBytes("id");
System.out.println("bytes: "+bytes.length); // prints "bytes: 16"

ByteBuffer buffer = ByteBuffer.allocate(16);
buffer = buffer.put(bytes);

// throws an java.nio.BufferUnderflowException
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();

我使用以下方法将字节数组存储到数据库中:

byte[] bytes = ByteBuffer.allocate(16)
    .putLong(leastSignificant)
    .putLong(mostSignificant).array();

【问题讨论】:

    标签: java arrays type-conversion bytebuffer bufferunderflowexception


    【解决方案1】:

    你可以的

    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    long leastSignificant = buffer.getLong(); 
    long mostSignificant = buffer.getLong(); 
    

    【讨论】:

      【解决方案2】:

      在将字节插入其中后,您必须使用flip() 方法重置ByteBuffer(从而允许 getLong() 调用从开始读取 - 偏移量 0):

      buffer.put(bytes);     // Note: no reassignment either
      
      buffer.flip();
      
      long leastSignificant = buffer.getLong();
      long mostSignificant = buffer.getLong();
      

      【讨论】:

        【解决方案3】:
        long getLong(byte[] b, int off) {
            return ((b[off + 7] & 0xFFL) << 0) +
                   ((b[off + 6] & 0xFFL) << 8) +
                   ((b[off + 5] & 0xFFL) << 16) +
                   ((b[off + 4] & 0xFFL) << 24) +
                   ((b[off + 3] & 0xFFL) << 32) +
                   ((b[off + 2] & 0xFFL) << 40) +
                   ((b[off + 1] & 0xFFL) << 48) +
                   (((long) b[off + 0]) << 56);
        }
        
        long leastSignificant = getLong(bytes, 0);
        long mostSignificant = getLong(bytes, 8);
        

        【讨论】:

          【解决方案4】:

          试试这个:

          LongBuffer buf = ByteBuffer.wrap(bytes).asLongBuffer();
          long l1 = buf.get();
          long l2 = buf.get();
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-05-13
            • 2012-06-06
            • 1970-01-01
            • 2023-03-09
            • 1970-01-01
            • 1970-01-01
            • 2019-07-31
            相关资源
            最近更新 更多