Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast a hexadecimal string to a class object

I have a class like this:

public class Fields implements java.io.Serializable{
    public short ID;
    public int SSN;
    public long Number;
}

and I have a hexadecimal string with the value like this which each 2 characters is representative of a byte:

String str="1000180018000540AC80D6487653E5000100D40B7900D4C3FFF2FAFF8985";

Now I want to cast this string to the above class object in a schema like this:

//ID has short type so we need 2 bytes
ID=4096; //(decimal value of 1000)

//SSN has integer type so we need 4 bytes
SSN=402659328; //(decimal value of 18001800)

//Number has long type so we need 8 bytes
Number=378492038049986131; //(decimal value of 0540AC80D6487653)

This casting can be implemented in c++ with <reinterpret_cast> so easily but as the Is there cast in Java similar to in C++ question is said, I can implement that with serialization in java. I think serialization can be used when we serialize a class object to the byte arrays at first and second we can de-serialize the obtained bytes to the primitive class object, which is different from my propose a little, because I have a string (like bytes) which I want to de-serialize that. So how can I do that?

like image 703
ahmadi morteza ali Avatar asked May 31 '26 20:05

ahmadi morteza ali


1 Answers

Java Serialization has a very specific data format and it doesn't help you parse data that you get with a different pre-defined format. But a ByteBuffer can be useful in parsing this kind of data.

First you need to transform your string into an actual byte[] array. I'll use a simple solution from this answer, feel free to pick another one that's more appropriate to your example:

byte[] data = DatatypeConverter.parseHexBinary(str);
ByteBuffer buffer = ByteBuffer.wrap(data);

buffer.order(ByteOrder.LITTLE_ENDIAN); // maybe!

short id = buffer.getShort();
int ssn = buffer.getInt();
long number = buffer.getLong();

Whether or not you need the order() call depends on what endianness your data is in. ByteBuffer defaults to BIG_ENDIAN, so you can just leave that call out if that's what you need.

like image 88
Joachim Sauer Avatar answered Jun 03 '26 08:06

Joachim Sauer



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!