byte类型怎么转成byte数组

有一个String

String e = "aa";

aa为十六进制数,通过方法把它转成byte

public static byte hextobyte(String in) {
        return (byte) Integer.parseInt(in, 16);

    }

转出后得到一个byte

byte f = hextobyte(e);

问:
现在要进行byte拼接
原先有一个byte

byte[] a = new byte[] { 0x01, (byte) 0xFF, 0x0A, 0x00, (byte) 0xAA, 0x13,};

现在要把byte f 和byte[] a进行拼接
怎么讲byte f转成byte 数组!

试一下下面这种方式

byte[] a = new byte[] { 0x01, (byte) 0xFF, 0x0A, 0x00, (byte) 0xAA, 0x13};
byte f = 0x02;
int lengA = a.length;
byte[] b = new byte[lengA*2];
System.arraycopy(a,0,b,0,lengA);
b[lengA]= f;

新建一个比较大的数组,记录数组结尾位置,在数组末尾加数据:

byte a[]=new byte[1024]; 
a[index] = f;

再声明个数组嘛,长度加1,把那个加进去

自己写个函数很简单,就是重新创建一个更大的数组,拷贝过去。
但是我们做应用开发的,追求的目标就要写那种一句话程序,链式调用的,读起来像英语句子一样流畅。你可以使用随便一个ArrayUtils,优雅一点。

Byte[] arr = new Byte[]{1,2,3};
ArrayUtils.add(arr, 4);

只需要引用一个Jar包

<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons-lang.version}</version>
</dependency>

aa是两个字符,单个char才能转byte.直接强转(byte)e[0]
拷贝的话aa是2个字节+f字节数组.Length=MaxLength
var max = new byte[MaxLength];
arraycopy(f,max,f.length);arraycopy(aa,f.length,max,0,aa.length);

问题解决请点采纳,急需C币下载。

arraycopy(原数组, 原数组的开始位置, 目标数组, 目标数组的开始位置, 拷贝个数)

byte[] a = new byte[] { 0x01, (byte) 0xFF, 0x0A, 0x00, (byte) 0xAA, 0x13,};
byte[] temp =  new byte[a.length + 1];
byte f = hextobyte(e);
System.arraycopy(a, 0, temp, 0, a.length);
temp[a.length] = f;
a = f;

你可以把 byte f = hextobyte(e); 改写成byte[] f = new byte[]{hextobyte(e)};
byte[] a = new byte[] { 0x01, (byte) 0xFF, 0x0A, 0x00, (byte) 0xAA, 0x13};
byte[] data3 = new byte[f.length + a.length];

System.arraycopy(f, 0, data3, 0, f.length);
System.arraycopy(a, 0, data3, f.length, a.length);

    最终得到的data3 就是你想要的结果,进行了拼接