I have a byte array, and i need to copy a snippet of the byte array to a char array.
Example:
I have:
byte[] b = {4, 3, 2, 1, 5, 0, 0, 0};
I want to copy to char array the position 2->5, to char array be like:
char[] c = {2, 1, 5, 0}
I tried this method but the final char array is a empty array.
import java.io.*;
import java.util.*;
public class Main
{
public static void main (String[]args)
{
byte[] b = {4, 3, 2, 1, 5, 0, 0, 0};
char[] c = byte2CharArray(b, 2, 4);
System.out.println ("Char array: " + Arrays.toString(c));
}
public static char[] byte2CharArray(byte[] array, int index, int size){
char[] ret = new char[size];
/* Verify if exist Character size bytes to get from index */
if(array.length >= (index + Character.BYTES)) {
for (int i = 0; index < size; i++, index++) {
ret[i] = (char)array[index];
}
}
return ret;
}
}
ret[i] = ret[i] = ...? Also, what is the point of casting abyteto achar?index < sizecondition, so @eparvan comment is correct. Also it is not clear how OP was going to get[2, 1, 5, 0]starting from index 0.index < size? That's wrong. E.g. if you wanted to copy 3 bytes starting at offset 7, then7 < 3is immediately false and nothing would get copied.array.length >= (index + Character.BYTES)need to evaluate totruefor anything? The length of the array is irrelevant toCharacter.BYTESfor your scenario.