반응형
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
반응형
'Program Tip' 카테고리의 다른 글
jQuery 이벤트에서 'this'의 값 제어 (0) | 2020.10.25 |
---|---|
불변 클래스가 필요한 이유는 무엇입니까? (0) | 2020.10.25 |
웹 앱의 '선택'에서 iPhone이 확대되지 않도록 방지 (0) | 2020.10.25 |
Facebook의 소셜 플러그인에 유동 폭을 설정할 수 있습니까? (0) | 2020.10.25 |
부트 스트랩을 위해 팝 오버에 닫기 버튼을 삽입하는 방법 (0) | 2020.10.25 |