【问题标题】:How to make a byte array with first eight bytes as current timestamp?如何制作一个前八个字节作为当前时间戳的字节数组?
【发布时间】:2016-11-01 18:24:32
【问题描述】:

我正在制作一个预定义大小的字节数组,如下所示:

private byte[] newPayload() {
  byte[] payload = new byte[100];
  Arrays.fill(payload, (byte) 1);
  return payload;
}

现在我想在它前面的同一个字节数组中添加 8 个字节的当前时间戳。

long time = System.currentTimeMillis();

所以前 8 个字节将是当前时间戳,其余 92 个字节将与我现在所做的相同。

【问题讨论】:

    标签: java arrays byte bytebuffer


    【解决方案1】:

    您可以使用 ByteBuffer 将long 转换为byte[]。您也可以使用System.arraycopy 将此byte[] 复制到邮件数组。请参考以下代码。

    ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
    buffer.putLong(time);
    byte[] timeBytes = buffer.array();
    System.arraycopy(timeBytes, 0, payload, 0, timeBytes.length);
    

    【讨论】:

    • 看起来,我找不到 Long 类的 BYTES?我只看到大小?
    • 你可以试试(Long.SIZE / Byte.SIZE)
    • 另外假设如果我有这个新的字节数组,现在我如何从有效负载字节数组中提取前 8 个字节并将它们转换为 long 并打印出来?
    • 希望这会有所帮助.. stackoverflow.com/questions/4485128/…
    • 是的,但我将如何仅从字节数组中提取前八个字节?
    猜你喜欢
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    相关资源
    最近更新 更多