Program Tip

Java-int를 4 바이트의 바이트 배열로 변환 하시겠습니까?

programtip 2020. 10. 25. 12:50
반응형

Java-int를 4 바이트의 바이트 배열로 변환 하시겠습니까?


중복 가능성 :
정수를 바이트 배열로 변환 (Java)

버퍼 길이를 4 바이트 크기의 바이트 배열에 저장해야합니다.

의사 코드 :

private byte[] convertLengthToByte(byte[] myBuffer)
{
    int length = myBuffer.length;

    byte[] byteLength = new byte[4];

    //here is where I need to convert the int length to a byte array
    byteLength = length.toByteArray;

    return byteLength;
}

이를 달성하는 가장 좋은 방법은 무엇입니까? 나중에 해당 바이트 배열을 다시 정수로 변환해야합니다.


yourInt다음 ByteBuffer과 같이 사용하여 바이트 로 변환 수 있습니다 .

return ByteBuffer.allocate(4).putInt(yourInt).array();

그렇게 할 때 바이트 순서 에 대해 생각해야 할 수도 있습니다 .


public static  byte[] my_int_to_bb_le(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_le(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.LITTLE_ENDIAN).getInt();
}

public static  byte[] my_int_to_bb_be(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_be(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.BIG_ENDIAN).getInt();
}

이것은 작동합니다.

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

여기에서 가져온 코드 입니다.

편집 이 스레드 에는 더 간단한 솔루션이 제공됩니다 .


int integer = 60;
byte[] bytes = new byte[4];
for (int i = 0; i < 4; i++) {
    bytes[i] = (byte)(integer >>> (i * 8));
}

참고 URL : https://stackoverflow.com/questions/6374915/java-convert-int-to-byte-array-of-4-bytes

반응형