How to merge 2 binarybyte array in java [duplicate] - java

This question already has answers here:
How to combine two byte arrays [duplicate]
(7 answers)
Closed 8 years ago.
I have 2 byte array like this:
byte a[i]=1;
byte b[i]=0;
I want to merge it so that the output result becomes "10". I try to use arraycopy and make new output
byte[] output=a.length+b.length;
but it still doesn't work like my expectation. Anybody knows how to solve it?

Try this.
byte[] first = getFirstBytes();
byte[] second = getSecondBytes();
List<Byte> listOfBytes = new ArrayList<Byte>(Arrays.<Byte>asList(first));
listOfBytes.addAll(Arrays.<Byte>asList(second));
byte[] combinedByte = listOfBytes.toArray(new byte[listOfBytes.size()]);

Try this
byte[] first = {1,2,4,56,6};
byte[] second = {4,5,7,9,2};
byte[] merged = new byte[first.length+second.length];
System.arraycopy(first,0,merged,0,first.length);
System.arraycopy(second,0,merged,first.length,second.length);
for(int i=0; i<merged.length;i++)
{
System.out.println(merged[i]);
}

Try this.
byte a[i] = 1;
byte b[i] = 0;
byte[] output = new byte[a.length + b.length];
for(int i = 0 ; i < output.length ; ++i)
{
if(i < a.length) output[i] = a[i];
else output[i] = b[i - a.length];
}

Related

Mix byte array android

I would like to mix audio byte array, but I didn't succeed to sum the array.(note i already added some silent bytes of 0 as padding before).
I have an ArrayList of byte[] which contains:
the first byte[] is header (44 bytes).
Following byte[] are raw data byte array to be mixed
Here is my code:
ArrayList<byte[]> ListAudio = new ArrayList<byte[]>();
byte[] header= WriteHeader(); //wav header 44 bytes
ListAudio.add(header);
for (byte[] b : audioTreatment.ListDataByte) {
ListAudio.add(b);
}
//calculate total length of audio
int length = 0;
for (byte[] array : ListAudio) {
length += array.length;
}
final int len = length;
final byte[] mixBytes = new byte[len];
for (byte[] array : ListAudio) {
for (int i = 44; i < len; ++i) {
mixBytes[i] += array[i];
// mixBytes[i]=(byte) ((bytes1[i]+bytes2[i]) / 2);
}
}
I found somewhere that the method to mix digital byte array is :
mixBytes[i]=(byte) ((bytes1[i]+bytes2[i]) / 2);
I don't arrive to include the calcul above, to sum the byte array.
How can i sum the bytes array from my ArrayList ?
you have to declare your sources to merge them
byte[] source1 = ListAudio.get(0); //first from list
byte[] source2 = ListAudio.get(1); //second from list
int length = Math.min(source1.length, source2.length);//length of new array
length = length - 44; //skipping 44 byte
byte[] dest = new byte[length];
for(int index = 0; index < length; index ++){
byte b1 = source1[index+44];
byte b2 = source2[index+44];
dest[index] = (byte) ((b1+b2) / 2);
}
That would merge the first two byte[] from your list.
If you want to merge other sources you can change them by selecting other byte[] from your List.
HINT
The length of the destination is declared as Math.min(a,b) but you can fill missing bytes with zeros if you want...
if you want to merge all arrays, you have to adjust your merge operation
mixing two bytes: mixBytes[i]=(byte) ((bytes1[i]+bytes2[i]) / 2);
mixing three bytes: mixBytes[i]=(byte) ((bytes1[i]+bytes2[i]+bytes3[i]) / 3);
mixing N bytes: mixBytes[i]=(byte) ((bytes1[i]+bytes2[i]+bytes3[i]+...+bytesN[i]) / N);
ok, for your code snipped it would be:
int length = ...;//length of result, either min or max as mentioned above, see HINT
byte[] mixBytes = new byte[length];
int amountAudio = ListAudio.size(); //amount of tracks in your list aka 'N'
int sum;
for(int index = 0; index < length; index++){
sum = 0;
for(byte[] source: ListAudio){
//adding all byte into one big integer
sum = sum + source[index]; //NOTE: watch for indexOutOfBoundsException
}
//afterward divide the big int through amount of Audio tracks in your list
mixBytes[index] = (byte)(sum / amountAudio);
}

Can't Convert an Int Array to ASCII

to the point.
I don't know what make my function error but here when i want to convert an int Array to ASCII character, i got some errors which says
java.lang.OutOfMemoryError: Failed to allocate a 51529974 byte allocation with 4194304 free bytes and 30MB
I think my function doesn't right enough to convert it.
Here is my function :
public static String[] DectoASCII(int[] resultXORDec,int jumKat) {
int length = jumKat;
String ASCIIfromDec[] = new String[jumKat];
for(int i=0;i<jumKat;i++) {
StringBuilder builder = new StringBuilder(length);
for (int j = length - 1; j >= 0; i--) {
builder.append((char) ((resultXORDec[j] >> (8 * i)) & 0xFF));
}
ASCIIfromDec[i]=builder.toString();
Log.d("ascifrom",ASCIIfromDec[i]);
}
return ASCIIfromDec;
}
}
Please master, help me. Is there any other way to convert int (Decimal) to ASCII code?
Thanks..
Well, I guess the j index does not change in this loop:
for (int j = length - 1; j >= 0; i--) {
builder.append((char) ((resultXORDec[j] >> (8 * i)) & 0xFF));
}
thus you have an infinite loop, so builder gets bigger and bigger.

What are the mask values for decoding websocket frames?

I know that ENCODED are the bytes array, but what is MASK, what are his values?
var DECODED = "";
for (var i = 0; i < ENCODED.length; i++) {
DECODED[i] = ENCODED[i] ^ MASK[i % 4];
}
I've found this example on the web, the question is how can I know what are the MASK values?
any hint or links please? but in the google examples I find only this type of code, but I wish to see explicitly the MASK values, any help please
pstream = new BufferedWriter(new OutputStreamWriter(csocket.getOutputStream(), StandardCharsets.UTF_8));
char[] buff = new char[4];
pstream.read(buf);
//now buf have that masks?
Right above that code snippet it says:
If the MASK bit was set (and it should be, for client-to-server messages), read the next 4 octets (32 bits); this is the masking key.
You can find the MASK bit in the data frame format description.
So the pseudocode could be extended to
var LEN = decodeLength(buffer);
var MASK = buffer.read(4);
var ENCODED = buffer.read(LEN);
var DECODED = new Buffer(LEN);
for (var i = 0; i < ENCODED.length; i++) {
DECODED[i] = ENCODED[i] ^ MASK[i % 4];
}

How to convert efficiently binary string to binary byte array in Java?

As an input I have binary string String a = "100110". As output I need to have binary byte array byte[] b = {1,0,0,1,1,0}.
For now I'm using
for (int i=0; i<a.length; i++) {
b[i]= Byte.parseByte(a.substring(i, i+1));
}
But this approach is too slow. Can any one give a better suggestion? Thank you
You can do it without making objects for substrings, like this:
for (int i=0; i<a.length; i++) {
b[i]= a.charAt(i)=='1' ? (byte)1 : (byte)0;
}
The reason your approach is slower is that each call to substring produces a new String object, which becomes eligible for garbage collection as soon as parseByte is done with it.
Assuming the input is valid...
byte[] b = new byte[a.length()];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) (a.charAt(i) - '0');
}
Makes an int[] instead of byte[] but I hope for points for elegance:
int[] a = "100110"
// Turn it into a stream.
.chars()
// Make '0'/'1' into 0/1
.map(c -> c - '0')
// Roll it into an array.
.toArray();

When using RandomAccessFile, does the file pointer update on it's own after a read?

I am trying to read and parse a few pieces of information from a file that will be stored in sequential order. ,a char[] of size 8 ,an int ,an int[] of size 8 and finally ,an int.
So, I am reading 56 bytes of information. I am using RandomAccessFile and was wondering if I needed to seek() after preforming each operation of readChar() and readInt() or if I can just call these methods one after the other. I guess this is more of a question about whether the file pointer will reset after each operation completes or if it's safe so assume that the fp will follows it's last location until the file is closed.
Here is what I've written:
int currentOffset = 128;
for(int i = 0; i<16; i++){
//Initialize nodes.
readDisk.seek(currentOffset);
char[] name = new char[8];
for(int j = 0; j<8; j++){
name[i] = readDisk.readChar();
}
int size = readDisk.readInt();
int[] blockPointers = new int[8];
for(int j = 0; j<8; j++){
blockPointers[i] = readDisk.readInt();
}
int used = readDisk.readInt();
Will the fp be at 156 after these operations? Thank you! Sorry if this is a silly question.
Yes, read moves file pointer by number of bytes read, try this
RandomAccessFile f = new RandomAccessFile("1.txt", "r");
f.readChar();
System.out.println(f.getFilePointer());
output
2

Categories