[java] 정수를 바이트 배열로 변환 (Java)

로 변환하는 가장 빠른 방법 IntegerByte Array무엇입니까?

예 : 0xAABBCCDD => {AA, BB, CC, DD}



답변

ByteBuffer 클래스를 살펴보십시오 .

ByteBuffer b = ByteBuffer.allocate(4);
//b.order(ByteOrder.BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN.
b.putInt(0xAABBCCDD);

byte[] result = b.array();

그 바이트 순서 보장하지만 설정 result[0] == 0xAA, result[1] == 0xBB, result[2] == 0xCCresult[3] == 0xDD.

또는 수동으로 수행 할 수 있습니다.

byte[] toBytes(int i)
{
  byte[] result = new byte[4];

  result[0] = (byte) (i >> 24);
  result[1] = (byte) (i >> 16);
  result[2] = (byte) (i >> 8);
  result[3] = (byte) (i /*>> 0*/);

  return result;
}

ByteBuffer클래스는하지만 같은 더러운 손의 작업을 위해 설계되었습니다. 실제로 개인 java.nio.Bits은 다음에 의해 사용되는 도우미 메소드를 정의합니다 ByteBuffer.putInt().

private static byte int3(int x) { return (byte)(x >> 24); }
private static byte int2(int x) { return (byte)(x >> 16); }
private static byte int1(int x) { return (byte)(x >>  8); }
private static byte int0(int x) { return (byte)(x >>  0); }


답변

사용 BigInteger:

private byte[] bigIntToByteArray( final int i ) {
    BigInteger bigInt = BigInteger.valueOf(i);
    return bigInt.toByteArray();
}

사용 DataOutputStream:

private byte[] intToByteArray ( final int i ) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    dos.writeInt(i);
    dos.flush();
    return bos.toByteArray();
}

사용 ByteBuffer:

public byte[] intToBytes( final int i ) {
    ByteBuffer bb = ByteBuffer.allocate(4);
    bb.putInt(i);
    return bb.array();
}


답변

이 기능을 사용하면 저에게 효과적입니다.

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

int를 바이트 값으로 변환합니다.


답변

구아바 를 좋아한다면 Ints클래스를 사용할 수 있습니다 .


의 경우 intbyte[]사용 toByteArray():

byte[] byteArray = Ints.toByteArray(0xAABBCCDD);

결과는 {0xAA, 0xBB, 0xCC, 0xDD}입니다.


그 반대는 fromByteArray()또는 fromBytes():

int intValue = Ints.fromByteArray(new byte[]{(byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD});
int intValue = Ints.fromBytes((byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD);

결과는 0xAABBCCDD입니다.


답변

당신이 사용할 수있는 BigInteger :

정수에서 :

byte[] array = BigInteger.valueOf(0xAABBCCDD).toByteArray();
System.out.println(Arrays.toString(array))
// --> {-86, -69, -52, -35 }

반환 된 배열은 숫자를 나타내는 데 필요한 크기이므로 1을 나타내는 크기가 1 일 수 있습니다. 그러나 int가 전달되면 크기는 4 바이트를 초과 할 수 없습니다.

문자열에서 :

BigInteger v = new BigInteger("AABBCCDD", 16);
byte[] array = v.toByteArray();

그러나 첫 번째 바이트가 더 높은 경우 0x7F(이 경우와 같이) BigInteger가 0x00 바이트를 배열의 시작 부분에 삽입하는 경우주의해야합니다. 양수 값과 음수 값을 구별하기 위해 필요합니다.


답변

ByteOrder를 올바르게 처리하는 간단한 솔루션 :

ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()).putInt(yourInt).array();


답변

안드로이드로 아주 쉽게

int i=10000;
byte b1=(byte)Color.alpha(i);
byte b2=(byte)Color.red(i);
byte b3=(byte)Color.green(i);
byte b4=(byte)Color.blue(i);