假设我有一个字符串
String myString = "the quick brown fox jumps over the lazy dog";
我将它转换为字节数组
byte[] myByteArray = myString.getBytes();
然后,假设我有一个整数
int myInt = 42;
然后我将其转换为字节
byte myByte = (byte) myInt;
现在,假设我想将 int 添加到字节数组中,以便当我打印该数组时,它会打印出来
the quick brown fox jumps over the lazy dog42
我试过了,但没用
byte[] newByteArray = new byte[myByteArray.length + 1];
System.arraycopy(myByteArray, 0, newByteArray, 0, myByteArray.length);
newByteArray[newByteArray.length-1] = myByte;
String finalString = new String(newByteArray);
System.out.println(finalString);
所有打印出来的是
the quick brown fox jumps over the lazy dog*
'*' 是 ASCII 字符 42。
那么,最简单的方法是什么?
编辑:
是的,我知道我可以将字符串“42”附加到其他字符串中,但我希望将整数值存储在字节数组中。我假设一个字节就是一个字节,它是 String 还是 int 并不重要,因为字节在底层就是 1 和 0。
最佳答案
怎么样:
String myString = "the quick brown fox jumps over the lazy dog";
int myInt = 42;
String temp = myString + String.valueOf(myInt);
byte[] myByteArray = temp.getBytes();
关于java - 如何将 "add"整数添加到 Java 字节数组的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33741425/