将long转换为byte数组并将其添加到另一个数组

将long转换为byte数组并将其添加到另一个数组,第1张

将long转换为byte数组并将其添加到另一个数组

有多种方法可以做到这一点

  • 使用

    ByteBuffer
    (最佳选择-简洁易读):

    byte[] bytes = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(someLong).array();
  • 您还可以使用

    DataOutputStream
    (更详细):

        ByteArrayOutputStream baos = new ByteArrayOutputStream();    DataOutputStream dos = new DataOutputStream(baos);    dos.writeLong(someLong);    dos.close();    byte[] longBytes = baos.toByteArray();
  • 最后,您可以手动执行此 *** 作(摘自
    LongSerializer
    Hector的代码)(较难阅读):
        byte[] b = new byte[8];    for (int i = 0; i < size; ++i) {      b[i] = (byte) (l >> (size - i - 1 << 3));    }

然后,您可以通过一个简单的循环将这些字节追加到现有数组中:

    // change this, if you want your long to start from     // a different position in the array    int start = 0;     for (int i = 0; i < longBytes.length; i ++) {       bytes[start + i] = longBytes[i];    }


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5428580.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-11
下一篇2022-12-11

发表评论

登录后才能评论

评论列表(0条)

    保存