使用包装 ByteArrayOutputStream 的 DataOutputStream
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()
DataOutputStream stream = new DataOutputStream(byteArrayOutputStream);
try {
stream.writeInt(i);
stream.writeShort(s0);
stream.writeShort(s1);
stream.writeShort(s2);
stream.flush();
} catch (IOException e) {
// this can't happen, but you still require a try catch block
}
byte[] array = byteArrayOutputStream.toByteArray();
如果您的代码可能正在使用无符号整数解析类似的字节数组,那么您会有点头疼。也就是说,您必须检查负数并适当地处理它们。例如。
int unsignedIntAsSignedInt = inStream.readInt();
long realData;
if (unsignedIntAsSignedInt < 0) {
realData = ((long) unsignedIntAsSignedInt) - (((long)Integer.MIN_VALUE) * 2);
} else {
realData = unsignedIntAsSignedInt;
}