how to convert byte[] to Byte[], and the other way around?

霸气de小男生 提交于 2020-01-09 04:17:10

问题


How to convert byte[] to Byte[], and also Byte[] to byte[], in the case of not using any 3rd party library? Is there a way to do it fast just using the standard library?


回答1:


Byte class is a wrapper for the primitive byte. This should do the work:

byte[] bytes = new byte[10];
Byte[] byteObjects = new Byte[bytes.length];

int i=0;    
// Associating Byte array values with bytes. (byte[] to Byte[])
for(byte b: bytes)
   byteObjects[i++] = b;  // Autoboxing.

....

int j=0;
// Unboxing Byte values. (Byte[] to byte[])
for(Byte b: byteObjects)
    bytes[j++] = b.byteValue();



回答2:


byte[] to Byte[] :

byte[] bytes = ...;
Byte[] byteObject = ArrayUtils.toObject(bytes);

Byte[] to byte[] :

Byte[] byteObject = new Byte[0];
byte[] bytes = ArrayUtils.toPrimitive(byteObject);



回答3:


You could use the toPrimitive method in the Apache Commons lang library ArrayUtils class, As suggested here - Java - Byte[] to byte[]




回答4:


Java 8 solution:

Byte[] toObjects(byte[] bytesPrim) {
    Byte[] bytes = new Byte[bytesPrim.length];
    Arrays.setAll(bytes, n -> bytesPrim[n]);
    return bytes;
}

Unfortunately, you can't do this to convert from Byte[] to byte[]. Arrays has setAll for double[], int[], and long[], but not for other primitive types.




回答5:


From byte[] to Byte[]:

    byte[] b = new byte[]{1,2};
    Byte[] B = new Byte[b.length];
    for (int i = 0; i < b.length; i++)
    {
        B[i] = Byte.valueOf(b[i]);
    }

From Byte[] to byte[] (using our previously-defined B):

    byte[] b2 = new byte[B.length];
    for (int i = 0; i < B.length; i++)
    {
        b2[i] = B[i];
    }



回答6:


byte[] toPrimitives(Byte[] oBytes)
{

    byte[] bytes = new byte[oBytes.length];
    for(int i = 0; i < oBytes.length; i++){
        bytes[i] = oBytes[i];
    }
    return bytes;

}

Inverse:

//byte[] to Byte[]
Byte[] toObjects(byte[] bytesPrim) {

    Byte[] bytes = new Byte[bytesPrim.length];
    int i = 0;
    for (byte b : bytesPrim) bytes[i++] = b; //Autoboxing
    return bytes;

}


来源:https://stackoverflow.com/questions/12944377/how-to-convert-byte-to-byte-and-the-other-way-around

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!