0

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;
    }
}
8
  • 1
    What is the point of ret[i] = ret[i] = ...? Also, what is the point of casting a byte to a char? Commented Jul 14, 2021 at 21:53
  • sub-array from 2 to 5 has size of 4, however you've passed 3 Commented Jul 14, 2021 at 21:54
  • @Andreas, OP uses index < size condition, so @eparvan comment is correct. Also it is not clear how OP was going to get [2, 1, 5, 0] starting from index 0. Commented Jul 14, 2021 at 21:57
  • index < size? That's wrong. E.g. if you wanted to copy 3 bytes starting at offset 7, then 7 < 3 is immediately false and nothing would get copied. Commented Jul 14, 2021 at 21:58
  • 1
    Why would this: array.length >= (index + Character.BYTES) need to evaluate to true for anything? The length of the array is irrelevant to Character.BYTES for your scenario. Commented Jul 14, 2021 at 21:58

1 Answer 1

1

Since changing byte[] elements to char[] elements makes little sense if those elements are to be treated both as numeric types, I assume you wish to have char representations of digits:

ret[i] = (char)(array[index] + '0');

Would be a quick and dirty way, but prefer the more precise

ret[i] = Character.forDigit(array[index], 10);

since it's wrong (in theory) to be assumptive about character codes. Both versions of course do the same thing but the former works by incrementing from the character code of the digit zero to form the character code of the digit required. The character code of zero in most encodings is 0x30 and the subsequent digits increment that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.