[实用的byte处理类]

场景:

1. C++可以使用std::string来缓存uint8_t的字节数组,比如在接收socket数据包时, 需要接收完整才可以处理某些数据,这时候就需要先缓存起来再处理。

2. 问题来了,,Java的String是存储的UNICODE双字节结构,而且只支持字符,不支持如\0这些字符,并不适合处理字节数据.

先看看Java提供字节处理有哪些类,但是都不具备临时缓存的功能.

1. java.lang.Byte 类: 处理String和byte类型之间的转换,包括支持基数.可惜最大只支持byte 1字节的大小转换.2. java.lang.System 类的 arraycopy处理数组之间的复制,对原始类型是值复制,对于对象类型就是调用clone方法(估计).static void arraycopy(Object src, int srcPos, Object dst, int dstPos, int length)Copies length elements from the array src, starting at offset srcPos, into the array dst, starting at offset dstPos. 3. java.util.Arrays 类static int binarySearch(byte[] array, byte value)Performs a binary search for value in the ascending sorted array array. static byte[] copyOf(byte[] original, int newLength)Copies newLength elements from original into a new array. static void sort(byte[] array)static String toString(byte[] array)Creates a String representation of the byte[] passed. static void fill(byte[] array, byte value)Fills the specified array with the specified element. static boolean equals(byte[] array1, byte[] array2)Compares the two arrays. static byte[] copyOfRange(byte[] original, int start, int end)Copies elements from original into a new array, from indexes start (inclusive) to end (exclusive). static <T> List<T> asList(T… array)Returns a List of the objects in the specified array.

方案:

1. 封装一个byte[]数组的处理类,参考std::string.

2. 临时的方案,时间关系没优化.

package com.androidassist.util;import java.util.Arrays;public class ByteUtils {private int size;private byte[] buffer;public byte[] getBuffer() {return buffer;}private final int kBufferSizeIncrease = 512;private final int kDefaultBufferSize = 1024;public ByteUtils() {buffer = new byte[kDefaultBufferSize];size = 0;}public long getSize() {return size;}public void setSize(int size) {this.size = size;}public ByteUtils append(byte[] buf, int length) {if (size + length > buffer.length) {buffer = Arrays.copyOf(buffer, buffer.length + kBufferSizeIncrease);}System.arraycopy(buf, 0, buffer, size, length);size += length;return this;}public void erase(int begin, int count) {if (begin + count > size) {size = begin;} else {int startIndex = begin + count;System.arraycopy(buffer, startIndex, buffer, begin, count);size -= count;}}public void clear(){buffer = new byte[kDefaultBufferSize];size = 0;}//public static void main(String[] args) {//ByteUtils bu = new ByteUtils();//byte[] buf = new byte[32];//Arrays.fill(buf, (byte)1);//bu.append(buf,buf.length);//buf = new byte[1024];//Arrays.fill(buf, (byte)2);//bu.append(buf,buf.length);//System.out.println(bu.getSize());//bu.erase(0, 30);//System.out.println(bu.getSize());//bu.erase(4, 50);//System.out.println(bu.getSize());//System.out.println(bu.getBuffer()[2]);//System.out.println(bu.getBuffer()[1]);//}}

方案:

1. 封装一个byte[]数组的处理类,参考std::string.

流转的时光,都成为命途中美丽的点缀,

[实用的byte处理类]

相关文章:

你感兴趣的文章:

标签云: