Friday, September 18, 2015

Initialize byte array in Java and converting byte array to String


Just like any other Array, Byte array also have  the same syntax.

Below is  just an example to initialize a byte array.


byte[] bytes = [69, 121, 101, 45, 62, 118, 101, 114, 61, 101, 98];

But when you try to initialize your byte array, you will get compile time errors some times for bigger values.

For ex :


byte[] bytes = [69, 121, 101, 45, 62, 118, 101, 114, 196, 195, 61, 101, 98];


That code won't compile and you'll see a compile time error at the numbers, 196,195. The reason is that, Byte can hold up to the values  -128 to 127 only since it is 8 bits. Values greater or lesser than that should explicitly cast to byte so that they become bytes and not int's.

Hence here is the array after the  cast from int to  byte.



byte[] bytes = {69, 121, 101, 45, 62, 118, 101, 114, (byte) 196, (byte) 195, 61, 101, 98};


If you see, we casted the int values to bytes so that they sit in place of bytes.



Converting byte array to String : -



 Here is a small example to convert out byte array to a String in required charset format.


  String data = new String(bytes, StandardCharsets.UTF_8); 



No comments:

Post a Comment