2011-03-20 23 views
24

Tengo dos byte[] matrices que son de longitud desconocida y simplemente quiero añadir uno al extremo de la otra, es decir:Al añadir un byte [] para el final de otro byte []

byte[] ciphertext = blah; 
byte[] mac = blah; 
byte[] out = ciphertext + mac; 

I han intentado usar arraycopy() pero parece que no funciona.

+1

posible duplicado de [manera fácil de concatenar dos matrices de bytes] (http://stackoverflow.com/questions/5513152/easy-way-to-concatenate-two-byte-arrays) – Ubunfu

Respuesta

49

Usando System.arraycopy(), algo así como lo siguiente debería funcionar:

// create a destination array that is the size of the two arrays 
byte[] destination = new byte[ciphertext.length + mac.length]; 

// copy ciphertext into start of destination (from pos 0, copy ciphertext.length bytes) 
System.arraycopy(ciphertext, 0, destination, 0, ciphertext.length); 

// copy mac into end of destination (from pos ciphertext.length, copy mac.length bytes) 
System.arraycopy(mac, 0, destination, ciphertext.length, mac.length); 
+0

¡Excelente! Gracias por la solución rápida. ¡Funciona como un encanto y parece tan simple ahora! – Mitch

+0

Creo que creará dificultades si no conocemos el tamaño de la matriz final de antemano. – Shashwat

12

tiene que declarar out como una matriz de bytes con una longitud igual a la longitud de ciphertext y mac añadido juntos, y luego copiar ciphertext sobre el comienzo de out y mac sobre el extremo, utilizando arraycopy.

byte[] concatenateByteArrays(byte[] a, byte[] b) { 
    byte[] result = new byte[a.length + b.length]; 
    System.arraycopy(a, 0, result, 0, a.length); 
    System.arraycopy(b, 0, result, a.length, b.length); 
    return result; 
} 
+0

Lo encontré más útil. – Sorter

5

Primero debe asignar una matriz de la longitud combinada, a continuación, utilizar arraycopy para llenarlo de ambas fuentes.

byte[] ciphertext = blah; 
byte[] mac = blah; 
byte[] out = new byte[ciphertext.length + mac.length]; 


System.arraycopy(ciphertext, 0, out, 0, ciphertext.length); 
System.arraycopy(mac, 0, out, ciphertext.length, mac.length); 
7

Las otras soluciones aportadas son grandes cuando desea agregar sólo 2 matrices de bytes, pero si desea mantener añadiendo varios byte [] trozos para hacer una sola:

byte[] readBytes ; // Your byte array .... //for eg. readBytes = "TestBytes".getBytes(); 

ByteArrayBuffer mReadBuffer = new ByteArrayBuffer(0) ; // Instead of 0, if you know the count of expected number of bytes, nice to input here 

mReadBuffer.append(readBytes, 0, readBytes.length); // this copies all bytes from readBytes byte array into mReadBuffer 
// Any new entry of readBytes, you can just append here by repeating the same call. 

// Finally, if you want the result into byte[] form: 
byte[] result = mReadBuffer.buffer(); 
3

escribí el siguiente procedimiento para la concatenación de varios array:

static public byte[] concat(byte[]... bufs) { 
    if (bufs.length == 0) 
     return null; 
    if (bufs.length == 1) 
     return bufs[0]; 
    for (int i = 0; i < bufs.length - 1; i++) { 
     byte[] res = Arrays.copyOf(bufs[i], bufs[i].length+bufs[i + 1].length); 
     System.arraycopy(bufs[i + 1], 0, res, bufs[i].length, bufs[i + 1].length); 
     bufs[i + 1] = res; 
    } 
    return bufs[bufs.length - 1]; 
} 

utiliza Arrays.copyOf

8

P al vez la forma más fácil:

ByteArrayOutputStream output = new ByteArrayOutputStream(); 

output.write(ciphertext); 
output.write(mac); 

byte[] out = output.toByteArray(); 
+0

El más fácil y quizás el mejor soportado como ByteArrayBuffer parece obsoleto. – pete