Reputation: 11951
I am trying to concatenate long and bytearray to another bytearray.
I tried like this :
byte[] value1= new byte[16];
byte[] value2= new byte[16];
byte[] finalvalue = new byte[value1.length + value2.length];
long ts = System.currentTimeMillis();
int val = 100;
ByteBuffer.wrap(value1).order(ByteOrder.LITTLE_ENDIAN).asLongBuffer().put(ts);
ByteBuffer.wrap(value2).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().put(val);
System.arraycopy(value1, 0, finalvalue, 0, value1.length);
System.arraycopy(value2, 0, finalvalue, value1.length,value2.length);
When I tried to print this, I am not getting the correct values. It printing like this
BYTEVALUE -95-15-4410659100000000002000000000000000
it should print like this
- BYTEVALUE- 1354707038625,100
Can anyone help me out where I am going wrong.
Help will be appreciated.
Update:
Use to print values using StringBuffer like this:
StringBuffer sb = new StringBuffer(finalvalue.length);
for (int i = 0; i < finalvalue.length; i++) {
sb.append(finalvalue[i]);
}
Upvotes: 0
Views: 184
Reputation: 69339
Your code is not doing what you think it is. Consider the following self-contained application:
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class ByteArrayTest {
public static void main(String[] args) {
byte[] value1 = new byte[16];
byte[] value2 = new byte[16];
byte[] finalvalue = new byte[value1.length + value2.length];
long ts = System.currentTimeMillis();
int val = 100;
ByteBuffer.wrap(value1).order(ByteOrder.LITTLE_ENDIAN).asLongBuffer()
.put(ts);
ByteBuffer.wrap(value2).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer()
.put(val);
System.arraycopy(value1, 0, finalvalue, 0, value1.length);
System.arraycopy(value2, 0, finalvalue, value1.length, value2.length);
printByteArray(finalvalue);
}
private static void printByteArray(final byte[] array) {
StringBuilder sb = new StringBuilder(array.length);
for (byte b : array) {
sb.append(String.format("%02X", b));
}
System.out.println(sb.toString());
}
}
The output of this is:
BE26086B3B010000000000000000000064000000000000000000000000000000
Splitting this into component parts, we can see why:
The first sixteen bytes are BE26086B3B0100000000000000000000
. This is your timestamp in little endian order. If you ignore the zero bytes, this converts to 1,354,710,394,558
in decimal, which is correct.
The second sixteen bytes are 64000000000000000000000000000000
, which is your hard-coded value 100
.
The zeroes represent the space in the byte arrays that you didn't use.
Upvotes: 2