How to convert an object to byte array in JAVA.
The easiest way to convert an object to byte array is to use the Object Serialization ObjectOutputStream.
However, there is a problem that object serialization is compatible only with Java.
Object serialization cannot be used for socket communication with heterogeneous (c language, .NET, etc.).
So the method I found is to use ByteArrayOutputStream.
Below is an example of converting a class object configured with 16 bytes to byte[].
To implement it in a functional form for general use, it would be necessary to use the concept of Java reflection.
public class ProtocolDto {
public byte sender;
public byte receiver;
public short cmd;
public short error;
public short warning;
public int reserved;
public int data_length;
}
ProtocolDto protocolDto = new ProtocolDto();
// Object to Byte[] 변환
byte[] dtoByteArray = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
try {
dataOutputStream.writeByte(protocolDto.sender);
dataOutputStream.writeByte(protocolDto.receiver);
dataOutputStream.writeShort(protocolDto.cmd);
dataOutputStream.writeShort(protocolDto.error);
dataOutputStream.writeShort(protocolDto.warning);
dataOutputStream.writeInt(protocolDto.reserved);
dataOutputStream.writeInt(protocolDto.data_length);
dataOutputStream.flush();
dtoByteArray = byteArrayOutputStream.toByteArray();
} finally {
dataOutputStream.close();
byteArrayOutputStream.close();
}
// Result 16bytes
System.out.println(dtoByteArray.length);
'ENGLISH' 카테고리의 다른 글
JAVA RSA Error - invalid key format (0) | 2021.01.24 |
---|---|
How to Auto-print an Infinite Ink Printer (0) | 2018.12.02 |
Infinite Ink Printer InkPad (0) | 2018.12.02 |
Tomcat Error - java.util.concurrent.ExecutionException:org.apache.catalina.LifeException (0) | 2018.12.02 |
Example of adding an Android app Adfit ad (0) | 2018.12.02 |