java - 从 ArrayOfByte 中逐字节提取

标签 java android

我有一个像这样的 ArrayOfByte:

byte[] arrayOfByte = new byte[1024]

它随机包含 1,2,3,4 的数组..

假设里面有大约100Byte的数据,

我的问题是如何从中提取字节数据: 如果我使用 Log.d(TAG, "arrayOfByte :"+arrayOfByte); 它将显示 arrayOfByte :[B@2b052c60

现在我想单独提取每个字节并显示:1,1,2,1,3,3,3,2,2,1,4,4,4,2,3,3,3 ... 像这样

更新: 谢谢Sumit Singh,它成功了..

现在假设我们显示:[1,1,1,2,3,2,2,2,1,1,1,0,0,0,0,0,0,0]

问题1:如何将这些值放入某些int[]系列

问题2:我可以从中删除一些起始元素并将其设为[2,2,1,1,1,0,0,0,0,0,0,0 ]

最佳答案

您可以使用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) 

它将返回字节数组的字符串表示形式,例如 1,1,2,1,3,3,3,2,2,1,4,4,4,2,3,3,3 所以

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

更新了下一个问题

答案1:

  • 有很多方法可以做到这一点,最简单的是迭代每个字节数组元素并将基元从 char 扩大到 int:JLS 5.1.2 Widening Primitive Conversion
  • 您可以使用ByteBuffer它是 NIO 的一部分,如下所示:

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

答案2:

对于这个问题也有很多方法,我建议使用 Arrays.copyOfRange 。它将返回具有给定范围的新数组。

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);

关于java - 从 ArrayOfByte 中逐字节提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16165266/

相关文章:

java - 使用 url 片段中的参数重新加载页面会在 vaadin 中添加额外的斜杠字符

java - 数组的 toString 方法

java - 可以在jtable的某些列中显示pdf作为下载链接吗?

java - 包含标签未显示在 LinearLayout 中

android - Flutter App 与几乎所有东西都不兼容?

java - MATLAB - 删除二进制文件的元素而不加载整个文件

Java数组打印出奇怪的数字和文本

android - 如何防止一次为多个 View 调用 onTouchEvent() 方法?

android - Genymotion-/usr/lib64/libX11.so.6 : undefined symbol: xcb_wait_for_reply64

android - Firestore - 从 POJO 更新文档