Implemented sub byting output data

This commit is contained in:
Ziver Koc 2016-04-15 17:58:19 +02:00
parent 40fbbe1012
commit 3edc220ed8
3 changed files with 29 additions and 6 deletions

View file

@ -4,6 +4,7 @@ package zutil.parser.binary;
import java.lang.reflect.Field;
import java.util.*;
import zutil.ByteUtil;
import zutil.ClassUtil;
import zutil.converter.Converter;
import zutil.parser.binary.BinaryStruct.*;
@ -113,11 +114,18 @@ public class BinaryFieldData {
try {
field.setAccessible(true);
if (field.getType() == Boolean.class || field.getType() == boolean.class)
return new byte[]{ (byte)(field.getBoolean(obj) ? 0x01 : 0x00) };
return ByteUtil.getBits(
new byte[]{ (byte)(field.getBoolean(obj) ? 0x01 : 0x00)},
getBitLength(obj));
else if (field.getType() == Integer.class || field.getType() == int.class)
return Converter.toBytes(field.getInt(obj));
return ByteUtil.getBits(
Converter.toBytes(field.getInt(obj)),
getBitLength(obj));
else if (field.getType() == String.class)
return ((String)(field.get(obj))).getBytes();
return ByteUtil.getReverseByteOrder(
ByteUtil.getBits(
((String)(field.get(obj))).getBytes(),
getBitLength(obj)));
else
throw new UnsupportedOperationException("Unsupported BinaryStruct field type: "+ getType());
} catch (IllegalAccessException e){

View file

@ -81,7 +81,7 @@ public class BinaryStructOutputStream {
byte[] data = field.getByteValue(struct);
int fieldBitLength = field.getBitLength(struct);
for (int i = (int) Math.ceil(fieldBitLength / 8.0) - 1; fieldBitLength > 0; fieldBitLength -= 8, --i) {
for (int i=(int)Math.ceil(fieldBitLength/8.0)-1; fieldBitLength>0; fieldBitLength-=8, --i) {
byte b = data[i];
if (restBitLength == 0 && fieldBitLength >= 8)
out.write(0xFF & b);

View file

@ -78,6 +78,21 @@ public class BinaryStructOutputStreamTest {
assertArrayEquals(new byte[]{(byte)0b0100_0000}, data);
}
@Test
public void basicStringTest() throws IOException {
BinaryStruct struct = new BinaryStruct() {
@BinaryField(index=1, length=8)
int i1 = Integer.MAX_VALUE;
@BinaryField(index=2, length=12*8)
public String s2 = "hello world!";
};
byte[] expected = "0hello world!".getBytes();
expected[0] = (byte)0xFF;
byte[] data = BinaryStructOutputStream.serialize(struct);
assertArrayEquals(expected, data);
}
@Test
public void customBinaryFieldTest() throws IOException {
@ -103,15 +118,15 @@ public class BinaryStructOutputStreamTest {
@Test
public void variableLengthFieldTest() throws IOException {
BinaryStruct struct = new BinaryStruct() {
@BinaryField(index=1, length=1)
@BinaryField(index=1, length=8)
private int s1 = 2;
@VariableLengthBinaryField(index=2, lengthField="s1")
private String s2 = "12345";
};
byte[] data = BinaryStructOutputStream.serialize(struct);
byte[] expected = "012".getBytes();
expected[0] = 2;
byte[] data = BinaryStructOutputStream.serialize(struct);
assertArrayEquals(expected, data);
}
}