development

바이트 배열을 숫자 값 (Java)으로 변환하는 방법은 무엇입니까?

big-blog 2020. 9. 17. 08:26
반응형

바이트 배열을 숫자 값 (Java)으로 변환하는 방법은 무엇입니까?


8 바이트 배열이 있고 해당 배열을 해당 숫자 값으로 변환하고 싶습니다.

예 :

byte[] by = new byte[8];  // the byte array is stored in 'by'

// CONVERSION OPERATION
// return the numeric value

위의 변환 작업을 수행 할 방법을 원합니다.


첫 번째 바이트가 최하위 바이트라고 가정합니다.

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value += ((long) by[i] & 0xffL) << (8 * i);
}

첫 번째 바이트가 가장 중요하지만 약간 다릅니다.

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value = (value << 8) + (by[i] & 0xff);
}

8 바이트 이상이면 long을 BigInteger바꾸십시오 .

오류를 수정 해준 Aaron Digulla에게 감사드립니다.


하나는 사용할 수 Buffer의 일부로 제공되는의 java.nio변환을 수행 할 수있는 패키지를.

여기서 소스 byte[]배열의 길이는 long값에 해당하는 크기 인 8 입니다.

먼저 byte[]배열을로 래핑 ByteBuffer한 다음 ByteBuffer.getLong메서드를 호출하여 long을 얻습니다 .

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 4});
long l = bb.getLong();

System.out.println(l);

결과

4

ByteBuffer.getLong의견에 방법 을 지적 해 주신 dfa에게 감사드립니다 .


이 상황에서는 적용 할 수 없지만 Buffers 의 아름다움은 여러 값을 가진 배열을 보는 것입니다.

예를 들어, 우리는 8 바이트 배열을 가지고, 우리는 두 가지로 볼 원했던 int우리 랩 수 값 byte[]의 어레이 ByteBufferA와 볼, IntBuffer에 의해 값을 얻었다 IntBuffer.get:

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 1, 0, 0, 0, 4});
IntBuffer ib = bb.asIntBuffer();
int i0 = ib.get(0);
int i1 = ib.get(1);

System.out.println(i0);
System.out.println(i1);

결과:

1
4

이것이 8 바이트 숫자 값인 경우 다음을 시도 할 수 있습니다.

BigInteger n = new BigInteger(byteArray);

UTF-8 문자 버퍼 인 경우 다음을 시도 할 수 있습니다.

BigInteger n = new BigInteger(new String(byteArray, "UTF-8"));

Simply, you could use or refer to guava lib provided by google, which offers utiliy methods for conversion between long and byte array. My client code:

    long content = 212000607777l;
    byte[] numberByte = Longs.toByteArray(content);
    logger.info(Longs.fromByteArray(numberByte));

You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.

new BigInteger(bytes).intValue();

or to denote polarity:

new BigInteger(1, bytes).intValue();

Complete java converter code for all primitive types to/from arrays http://www.daniweb.com/code/snippet216874.html


Each cell in the array is treated as unsigned int:

private int unsignedIntFromByteArray(byte[] bytes) {
int res = 0;
if (bytes == null)
    return res;


for (int i=0;i<bytes.length;i++){
    res = res | ((bytes[i] & 0xff) << i*8);
}
return res;
}

참고URL : https://stackoverflow.com/questions/1026761/how-to-convert-a-byte-array-to-its-numeric-value-java

반응형