2바이트 어레이를 쉽게 연결하는 방법
개의 간단한 요?byte
★★★★★★★★★★★★★★★★★?
말합니다,
byte a[];
byte b[];
두 개를 연결할 수 있을까요?byte
에 byte
array?
가장 우아한 은 ' 좋다' 입니다.ByteArrayOutputStream
.
byte a[];
byte b[];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
outputStream.write( a );
outputStream.write( b );
byte c[] = outputStream.toByteArray( );
가장 간단:
byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
여기 Guava를 사용한 멋진 솔루션이 있습니다.com.google.common.primitives.Bytes
:
byte[] c = Bytes.concat(a, b);
이 방법의 장점은 다음과 같이 varargs 시그니처가 있다는 것입니다.
public static byte[] concat(byte[]... arrays)
즉, 단일 메서드콜로 임의의 수의 어레이를 연결할 수 있습니다.
또 다른 가능성은java.nio.ByteBuffer
.
뭐랄까
ByteBuffer bb = ByteBuffer.allocate(a.length + b.length + c.length);
bb.put(a);
bb.put(b);
bb.put(c);
byte[] result = bb.array();
// or using method chaining:
byte[] result = ByteBuffer
.allocate(a.length + b.length + c.length)
.put(a).put(b).put(c)
.array();
처음에 할당합니다(예: " "로)".따라서 할당 라인이 필요합니다(예:array()
는 오프셋, 위치 또는 제한을 고려하지 않고 백업 배열을 반환합니다).
또 다른 방법은 유틸리티 함수를 사용하는 것입니다(필요에 따라 범용 유틸리티 클래스의 정적 메서드로 만들 수 있습니다).
byte[] concat(byte[]...arrays)
{
// Determine the length of the result array
int totalLength = 0;
for (int i = 0; i < arrays.length; i++)
{
totalLength += arrays[i].length;
}
// create the result array
byte[] result = new byte[totalLength];
// copy the source arrays into the result array
int currentIndex = 0;
for (int i = 0; i < arrays.length; i++)
{
System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
currentIndex += arrays[i].length;
}
return result;
}
다음과 같이 호출합니다.
byte[] a;
byte[] b;
byte[] result = concat(a, b);
또, 3, 4, 5 어레이의 접속에도 대응합니다.
이렇게 하면 읽기 및 유지보수가 매우 쉬운 고속 어레이 복사 코드의 이점을 얻을 수 있습니다.
byte[] result = new byte[a.length + b.length];
// copy a to result
System.arraycopy(a, 0, result, 0, a.length);
// copy b to result
System.arraycopy(b, 0, result, a.length, b.length);
찮 if면면 ifByteBuffer
2개의 @secfranz를 할 수 .byte[]
에 ( 많은) 줄에 이렇게
byte[] c = ByteBuffer.allocate(a.length+b.length).put(a).put(b).array();
Apache Commons Lang과 같은 Clean Code용 서드파티 라이브러리를 사용하여 다음과 같이 사용할 수 있습니다.
byte[] bytes = ArrayUtils.addAll(a, b);
2대 또는 복수의 어레이에서는, 다음과 같은 심플하고 깨끗한 유틸리티 방법을 사용할 수 있습니다.
/**
* Append the given byte arrays to one big array
*
* @param arrays The arrays to append
* @return The complete array containing the appended data
*/
public static final byte[] append(final byte[]... arrays) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
if (arrays != null) {
for (final byte[] array : arrays) {
if (array != null) {
out.write(array, 0, array.length);
}
}
}
return out.toByteArray();
}
2개의 PDF 바이트 어레이를 Marge합니다.
PDF 를 포함한 2 개의 바이트 배열을 Marge 하는 경우는, 이 논리는 기능하지 않습니다.Apache의 PDFbox와 같은 서드파티 툴을 사용해야 합니다.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
mergePdf.addSource(new ByteArrayInputStream(a));
mergePdf.addSource(new ByteArrayInputStream(b));
mergePdf.setDestinationStream(byteArrayOutputStream);
mergePdf.mergeDocuments();
c = byteArrayOutputStream.toByteArray();
어레이의 크기를 조작하고 싶지 않은 경우는, 스트링 접속의 매직만을 사용해 주세요.
byte[] c = (new String(a, "l1") + new String(b, "l1")).getBytes("l1");
또는 코드의 어딘가를 정의합니다.
// concatenation charset
static final java.nio.charset.Charset cch = java.nio.charset.StandardCharsets.ISO_8859_1;
및 사용
byte[] c = (new String(a, cch) + new String(b, cch)).getBytes(cch);
이 '아', '아', '2'를 할 수 있습니다.+
덧셈 연산자
다."l1"
★★★★★★★★★★★★★★★★★」ISO_8859_1
각 문자를 1바이트로 인코딩하는 서부 라틴어 1 문자 집합을 나타냅니다.되지 않기 단, 항상 됩니다).char
서명되어 있지 않습니다.따라서 적어도 Oracle에서 제공하는 런타임의 경우 모든 바이트가 올바르게 "디코딩"된 후 다시 "인코딩"됩니다.
문자열은 바이트 어레이를 상당히 확장하므로 추가 메모리가 필요합니다.문자열도 삽입될 수 있으므로 쉽게 제거할 수 없습니다.문자열도 불변하기 때문에 문자열 내의 값은 파기할 수 없습니다.따라서 기밀 배열을 이 방법으로 연결하거나 더 큰 바이트 배열에 이 방법을 사용하지 마십시오.이 어레이 연결 방식은 일반적인 솔루션이 아니기 때문에 수행 중인 작업을 명확하게 지시하는 것도 필요합니다.
이게 내 방식이야!
public static byte[] concatByteArrays(byte[]... inputs) {
int i = inputs.length - 1, len = 0;
for (; i >= 0; i--) {
len += inputs[i].length;
}
byte[] r = new byte[len];
for (i = inputs.length - 1; i >= 0; i--) {
System.arraycopy(inputs[i], 0, r, len -= inputs[i].length, inputs[i].length);
}
return r;
}
특징:
- varargs 사용(
...
)는 임의의 바이트 수로 호출됩니다[ ) 。 - 사용하다
System.arraycopy()
머신 고유의 네이티브 코드로 구현되어 고속 동작을 보증합니다. - 필요한 정확한 크기로 새 바이트[]를 만듭니다.
- 할당량 감소
int
변수:i
그리고.len
변수입니다. - 상수와의 빠른 비교.
주의:
이를 위한 더 좋은 방법은 @Jonathan 코드를 복사하는 것입니다.이 문제는 네이티브 변수 배열에서 발생합니다. Java는 이 데이터 유형이 다른 함수에 전달될 때 새로운 변수를 생성하기 때문입니다.
이미 Guava 라이브러리를 로드하는 경우 정적 방법을 사용할 수 있습니다.concat(byte[]... arrays)
부터com.google.common.primitives.Bytes
:
byte[] c = Bytes.concat(a, b);
다음은 의 스탠드아론 소스입니다.concat(byte[]... arrays)
Kevin Bourrillion의 메서드:
public static byte[] concat(byte[]... arrays) {
int length = 0;
for (byte[] array : arrays) {
length += array.length;
}
byte[] result = new byte[length];
int pos = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
언급URL : https://stackoverflow.com/questions/5513152/easy-way-to-concatenate-two-byte-arrays
'programing' 카테고리의 다른 글
Vue setup() 메서드로 Vuex 스토어에 액세스하는 방법 (0) | 2022.07.02 |
---|---|
Electron-Vue 응용 프로그램의 상태는 어디에 저장됩니까? (0) | 2022.07.02 |
VueCli 3을 사용하여 index.html의 app.js 파일 이름을 변경하는 방법 (0) | 2022.07.02 |
영숫자 텍스트에서 선행 0을 삭제하려면 어떻게 해야 합니까? (0) | 2022.07.02 |
Vue: .vue 템플릿에서 pug 언어가 인식되지 않았습니다. (0) | 2022.07.02 |