0

For example, I have a class that has short, byte, int type member variable.

class A{
    short a;
    byte b;
    int c;
}

If I serialize or convert to byte array, the Array is unexpected value.

if values like,

A a = new A();
a.a = 3;
a.b = 0x02;
a.c = 15;

then, I expect its bytes as,

00 03 02 00 00 00 0F

So... How to Serialize Object like that?

It needs my socket server... other language

6
  • What values do you receive after serialization? Commented Jan 13, 2016 at 9:39
  • long, int, short, byte, float, double ... normal values. Commented Jan 13, 2016 at 9:40
  • No, question is about which exactly bytes do you receive output? Commented Jan 13, 2016 at 9:43
  • How do you serialize it now? And what does that produce instead of the expected output? Commented Jan 13, 2016 at 9:46
  • my server receive bytes data. but I don't have sample. I just want to know how to make the object compact byte array Commented Jan 13, 2016 at 9:47

2 Answers 2

3

If you want a byte array you can do this. However if you are using something like DataOutputStream it's best to just call writeInt, writeShort, ...

A a = new A();
a.a = 3;
a.b = 0x02;
a.c = 15;

ByteBuffer bb = ByteBuffer.allocate(7).order(ByteOrder.BIG_ENDIAN);
bb.putShort(a.a).put(a.b).putInt(a.c).flip();
byte[] buffer = bb.array();
for (byte b : buffer)
    System.out.printf("%02X ", b);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use reflection to get all fields in the class, and loop them to convert to an array of bytes.

If all your fields are Number (i.e. not references nor boolean), you can convert and collect them to a List of Byte as follows:

List<Byte> list = new ArrayList<>();
for (Field field : A.class.getDeclaredFields()) {
    // Do something else if field is not a Number
    // ...

    // Otherwise, convert and collect into list
    Number n = (Number) field.get(a);
    int size = n.getClass().getDeclaredField("BYTES").getInt(null);
    IntStream.range(0, size)
        .mapToObj(i -> (byte) (n.longValue() >> 8*(size-i-1)))
        .forEach(b -> list.add(b));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.