Kiran
Kiran

Reputation: 3133

extracting Byte by Byte from an ArrayOfByte

i have an ArrayOfByte like this:

byte[] arrayOfByte = new byte[1024]

It contains array of 1,2,3,4 inside it randomly..

Assume there are about 100 Byte data in it,

my question is how to extract byte by byte data from it : it i use Log.d(TAG, "arrayOfByte :"+arrayOfByte); it will display arrayOfByte :[B@2b052c60

now i want to extract each byte separately and display: 1,1,2,1,3,3,3,2,2,1,4,4,4,2,3,3,3... like this

UPDATE: Thanks Sumit Singh, it worked ..

now suppose we display: [1,1,1,2,3,2,2,2,1,1,1,0,0,0,0,0,0,0]

Question1: how to put these values in some int[] series

Question2: can i delete few starting elements from it and make it [2,2,1,1,1,0,0,0,0,0,0,0]

Upvotes: 2

Views: 214

Answers (1)

Sumit Singh
Sumit Singh

Reputation: 15896

You can use Arrays.toString(byte[] a):

Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(byte). Returns "null" if a is null.

Arrays.toString(arrayOfByte) 

It will return String representation of your byte array like 1,1,2,1,3,3,3,2,2,1,4,4,4,2,3,3,3 So

Log.d(TAG, "arrayOfByte :"+ Arrays.toString(arrayOfByte));

Updated for next Questions

Ans 1:

  • There are many ways to do this simplest is iterate over each byte array element and widening primitives from char to int: JLS 5.1.2 Widening Primitive Conversion
  • You can use ByteBuffer which is part of NIO like following:

    int[] intArray = ByteBuffer.wrap(arrayOfByte).asIntBuffer().array()

Ans 2:

For this question also there are lots of way, one i'm suggesting is use Arrays.copyOfRange. It will return new array with your given range.

Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case (byte)0 is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from.

byte[] newByteArray = Arrays.copyOfRange(arrayOfByte, startIndex, endIndex);

Upvotes: 5

Related Questions