ProgramingTip

byte []를 Byte []로 변환하는 방법과 그 반대의 방법은 무엇입니까?

bestdevel 2020. 11. 27. 21:04
반응형

byte []를 Byte []로 변환하는 방법과 그 반대의 방법은 무엇입니까?


라이브러리를 사용하지 않는 경우 byte []를 Byte []로, Byte []를 byte []로 변환하는 방법은 무엇입니까? 표준 라이브러리를 사용하여 신속하게 할 수있는 방법이 있습니까?


Byteclass는 프리미티브 래퍼 입니다 byte. 이 작업을 수행해야합니다.

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();

바이트 []-바이트 [] :

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

바이트 []-바이트 [] :

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

Apache Commons lang 라이브러리 ArrayUtils 클래스에서 toPrimitive 메소드를 사용할 수 있습니다. 여기에 제안 된대로 -Java -Byte [] to byte []


Java 8 솔루션 :

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

불행하게도,은 CHAPTER 2 에서이 당신 작업을 수행 할 수 있습니다 Byte[]byte[]. ArrayssetAll에 대한 double[], int[]그리고 long[]또 다른 원시 형을.


byte []에서 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]);
    }

Byte []에서 byte []로 (이전에 정의 된 B) :

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

byte[] toPrimitives(Byte[] oBytes)
{

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

}

역 :

//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;

}

참고 URL : https://stackoverflow.com/questions/12944377/how-to-convert-byte-to-byte-and-the-other-way-around

반응형