【问题标题】:How to merge 2 binarybyte array in java [duplicate]如何在java中合并2个二进制字节数组[重复]
【发布时间】:2014-12-17 05:05:02
【问题描述】:

我有这样的 2 字节数组:

byte a[i]=1;
byte b[i]=0;

我想合并它,使输出结果变成“10”。我尝试使用 arraycopy 并制作新的输出

byte[] output=a.length+b.length;

但它仍然不像我的预期那样工作。有人知道怎么解决吗?

【问题讨论】:

标签: java bytearray


【解决方案1】:

试试这个。

byte[] first = getFirstBytes();
byte[] second = getSecondBytes();

List<Byte> listOfBytes = new ArrayList<Byte>(Arrays.<Byte>asList(first));
listOfBytes.addAll(Arrays.<Byte>asList(second));

byte[] combinedByte = listOfBytes.toArray(new byte[listOfBytes.size()]);

【讨论】:

    【解决方案2】:

    试试这个

         byte[] first = {1,2,4,56,6};
         byte[] second = {4,5,7,9,2};
         byte[] merged = new byte[first.length+second.length];
    
         System.arraycopy(first,0,merged,0,first.length);
         System.arraycopy(second,0,merged,first.length,second.length);
    for(int i=0; i<merged.length;i++)
    {
        System.out.println(merged[i]);
    }
    

    【讨论】:

    • 谢谢你,你的例子有效!
    • user3698011 没明白你的意思
    【解决方案3】:

    试试这个。

    byte a[i] = 1;
    byte b[i] = 0;
    
    byte[] output = new byte[a.length + b.length];
    
    for(int i = 0 ; i < output.length ; ++i)
    {
        if(i < a.length) output[i] = a[i];
        else output[i] = b[i - a.length];
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 2013-09-29
      • 1970-01-01
      • 2019-12-20
      • 2022-08-07
      • 2017-04-03
      • 2019-10-29
      • 2011-08-06
      • 2019-09-06
      相关资源
      最近更新 更多