Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from object to byte array and back in java

I have two classes: TcpPacket and IpPacket. The tcpPacket should be stored in the data field of the ip packet. How can I reliably convert the tcpPacket object to a byte array so that i can store it in the IpPacket's data field? And upon receiving the packet on the other side, how to reliably convert it back into a packet object?

public static final class TcpPacket {
    int source;
    int destination;

    public Packet( int source, int destination ) {
        this.source = source;
        this.destination = destination;
    }

    public String toString() {
        return "Source: " + source + ", Dest: " + destination;
    }
}

public static final class IpPacket {
    byte[] data;

    IpPacket( byte[] data ){
        this.data = data;
    }
}

TcpPacket tcpPacket = new TcpPacket( <someint>, <someint> );

// the following doesn't work because tcppacket is not a byte array.
IpPacket ipPacket = new IpPacket( tcpPacket );

How is this usually done?

Thanks Maricruzz

like image 723
Maricruzz Avatar asked Jun 27 '26 19:06

Maricruzz


1 Answers

This should work, just cast the object to your class after receiving it from the serialize/deserialize function.

public static byte[] objToByte(TcpPacket tcpPacket) throws IOException {
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    ObjectOutputStream objStream = new ObjectOutputStream(byteStream);
    objStream.writeObject(tcpPacket);

    return byteStream.toByteArray();
}

public static Object byteToObj(byte[] bytes) throws IOException, ClassNotFoundException {
    ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
    ObjectInputStream objStream = new ObjectInputStream(byteStream);

    return objStream.readObject();
}
like image 134
BaN3 Avatar answered Jun 30 '26 07:06

BaN3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!