user5313398 user5313398 - 1 year ago 86
Java Question

How to send all byte into single array and later xor between the bytes?

I have socket application and I can read byte by byte and I need push all the byte into one single array.
I read like below.So I will have 12+bodylen bytes.

int messageID = r.readUnsignedShort();
int bodyLen = r.readUnsignedShort();
byte[] phoneNum = new byte[6];
int serialNum = r.readUnsignedShort();
byte[] messageBody = new byte[bodyLen];
byte checkCode = r.readByte();

My challenge is how to push all the byte into one fullMessage and there after I need to xor between each of this bytes and get the results as byte too.

byte[] fullMessage = new byte[12+bodyLen];

Answer Source

If you dont need to have everything in separate and you need all in single array, after reading bodyLen you can do something like this:

int messageID = r.readUnsignedShort();
int bodyLen = r.readUnsignedShort();       
byte[] fullMessage=new byte[12+bodyLen];

Here fullMessage will contain all the data you are reading step by step in your code in single array.

But if you need all the parts to be read separately: read below

To concatenate arrays and other elements into array use ByteBuffer#put(byte[]). After work is done, get the array from buffer using .array() method of ByteBuffer

byte[] fullMessage=byteBuffer.array();

Later on, iterate over array and do required work

for(int i=0,s=fullMessage.lengthl;i<s;i++){
     // do your XOR operations -> xor operator is ^
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download