栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将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];    }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/453054.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号