com.igormaznitsa.jbbp.io.JBBPByteOrder Java Examples

The following examples show how to use com.igormaznitsa.jbbp.io.JBBPByteOrder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HOBETAPlugin.java    From zxpoly with GNU General Public License v3.0 6 votes vote down vote up
private boolean writeDataBlockAsHobeta(final File file, final String name, final byte type,
                                       final int start, final byte[] data) throws IOException {
  final byte[] header = JBBPOut.BeginBin()
      .ByteOrder(JBBPByteOrder.LITTLE_ENDIAN)
      .Byte(ensureHobetaName(name))
      .Byte(type)
      .Short(start)
      .Short(data.length)
      .ByteOrder(JBBPByteOrder.BIG_ENDIAN)
      .Short(Math.max(1, (data.length / 256) + ((data.length & 0xFF) == 0 ? 0 : 1)))
      .End()
      .toByteArray();

  final byte[] full = JBBPOut.BeginBin()
      .ByteOrder(JBBPByteOrder.LITTLE_ENDIAN)
      .Byte(header)
      .Short(makeCRC(header))
      .Byte(data)
      .End()
      .toByteArray();
  return saveDataToFile(file, full);
}
 
Example #2
Source File: JBBPTextWriter.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param out                  a writer to be wrapper, must not be null.
 * @param byteOrder            byte order to be used for converting, must not be null.
 * @param lineSeparator        line separator, must not be null.
 * @param radix                radix, must be 2..36.
 * @param valuePrefix          prefix before each value, can be null.
 * @param startValueLinePrefix prefix before the first value on line, can be
 *                             null.
 * @param commentPrefix        prefix before comments, can be null.
 * @param hrPrefix             prefix for horizontal rule
 * @param valueDelimiter       delimiter between values, can be null
 */
public JBBPTextWriter(
    final Writer out,
    final JBBPByteOrder byteOrder,
    final String lineSeparator,
    final int radix,
    final String valuePrefix,
    final String startValueLinePrefix,
    final String commentPrefix,
    final String hrPrefix,
    final String valueDelimiter) {
  super(out);
  JBBPUtils.assertNotNull(lineSeparator, "Line separator must not be null");

  this.flagCommentsAllowed = true;
  this.prefixHR = hrPrefix == null ? "" : hrPrefix;
  this.lineSeparator = lineSeparator;

  JBBPUtils.assertNotNull(out, "Writer must not be null");
  ByteOrder(byteOrder);
  SetValueSeparator(valueDelimiter);
  SetValueLinePrefix(startValueLinePrefix);
  SetCommentPrefix(commentPrefix);
  SetValuePrefix(valuePrefix);
  Radix(radix);
}
 
Example #3
Source File: JBBPTextWriter.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
/**
 * Print short value.
 *
 * @param value short value to be printed
 * @return the context
 * @throws IOException it will be thrown for transport errors
 */
public JBBPTextWriter Short(final int value) throws IOException {
  ensureValueMode();
  String convertedByExtras = null;
  for (final Extra e : this.extras) {
    convertedByExtras = e.doConvertShortToStr(this, value & 0xFFFF);
    if (convertedByExtras != null) {
      break;
    }
  }

  if (convertedByExtras == null) {
    final long valueToWrite;
    if (this.byteOrder == JBBPByteOrder.LITTLE_ENDIAN) {
      valueToWrite = JBBPUtils.reverseByteOrder(value, 2);
    } else {
      valueToWrite = value;
    }
    printValueString(JBBPUtils.ensureMinTextLength(JBBPUtils.ulong2str(valueToWrite & 0xFFFFL, this.radix, CHAR_BUFFER), this.maxCharsRadixForShort, '0', 0));
  } else {
    printValueString(convertedByExtras);
  }
  return this;
}
 
Example #4
Source File: JBBPTextWriter.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
/**
 * Print double value.
 *
 * @param value double value to be printed
 * @return the context
 * @throws IOException it will be thrown for transport errors
 * @since 1.4.0
 */
public JBBPTextWriter Double(final double value) throws IOException {
  ensureValueMode();
  String convertedByExtras = null;
  for (final Extra e : this.extras) {
    convertedByExtras = e.doConvertDoubleToStr(this, value);
    if (convertedByExtras != null) {
      break;
    }
  }

  if (convertedByExtras == null) {
    final double valueToWrite;
    if (this.byteOrder == JBBPByteOrder.LITTLE_ENDIAN) {
      valueToWrite = Double.longBitsToDouble(JBBPFieldLong.reverseBits(Double.doubleToLongBits(value)));
    } else {
      valueToWrite = value;
    }
    printValueString(JBBPUtils.ensureMinTextLength(JBBPUtils.double2str(valueToWrite, this.radix), this.maxCharsRadixForShort, '0', 0));
  } else {
    printValueString(convertedByExtras);
  }
  return this;
}
 
Example #5
Source File: JBBPTextWriter.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
/**
 * Print integer value
 *
 * @param value value to be printed
 * @return the context
 * @throws IOException it will be thrown for transport error
 */
public JBBPTextWriter Int(final int value) throws IOException {
  ensureValueMode();

  String convertedByExtras = null;
  for (final Extra e : this.extras) {
    convertedByExtras = e.doConvertIntToStr(this, value);
    if (convertedByExtras != null) {
      break;
    }
  }

  if (convertedByExtras == null) {
    final long valueToWrite;
    if (this.byteOrder == JBBPByteOrder.LITTLE_ENDIAN) {
      valueToWrite = JBBPUtils.reverseByteOrder(value, 4);
    } else {
      valueToWrite = value;
    }
    printValueString(JBBPUtils.ensureMinTextLength(JBBPUtils.ulong2str(valueToWrite & 0xFFFFFFFFL, this.radix, CHAR_BUFFER), this.maxCharsRadixForInt, '0', 0));
  } else {
    printValueString(convertedByExtras);
  }
  return this;
}
 
Example #6
Source File: JBBPTextWriter.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
/**
 * Print long value
 *
 * @param value value to be printed
 * @return the context
 * @throws IOException it will be thrown for transport errors
 */
public JBBPTextWriter Long(final long value) throws IOException {
  ensureValueMode();

  String convertedByExtras = null;
  for (final Extra e : this.extras) {
    convertedByExtras = e.doConvertLongToStr(this, value);
    if (convertedByExtras != null) {
      break;
    }
  }

  if (convertedByExtras == null) {
    final long valueToWrite;
    if (this.byteOrder == JBBPByteOrder.LITTLE_ENDIAN) {
      valueToWrite = JBBPUtils.reverseByteOrder(value, 8);
    } else {
      valueToWrite = value;
    }
    printValueString(JBBPUtils.ensureMinTextLength(JBBPUtils.ulong2str(valueToWrite, this.radix, CHAR_BUFFER), this.maxCharsRadixForLong, '0', 0));
  } else {
    printValueString(convertedByExtras);
  }
  return this;
}
 
Example #7
Source File: JBBPUtils.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
/**
 * Convert chars of a string into a byte array contains the unicode codes.
 *
 * @param byteOrder the byte order for the operation, must not be null
 * @param str       the string which chars should be written, must not be null
 * @return the byte array contains unicodes of the string written as byte
 * pairs
 * @since 1.1
 */
public static byte[] str2UnicodeByteArray(final JBBPByteOrder byteOrder, final String str) {
  final byte[] result = new byte[str.length() << 1];
  int index = 0;
  for (int i = 0; i < str.length(); i++) {
    final int val = str.charAt(i);
    switch (byteOrder) {
      case BIG_ENDIAN: {
        result[index++] = (byte) (val >> 8);
        result[index++] = (byte) val;
      }
      break;
      case LITTLE_ENDIAN: {
        result[index++] = (byte) val;
        result[index++] = (byte) (val >> 8);
      }
      break;
      default:
        throw new Error("Unexpected byte order [" + byteOrder + ']');
    }
  }
  return result;
}
 
Example #8
Source File: Spec256ZipPlugin.java    From zxpoly with GNU General Public License v3.0 6 votes vote down vote up
private byte[] makeSnaHeaderFromZ80Header(
    final Z80InZXPOutPlugin.Z80MainHeader z80header,
    final boolean pcOnStack
) throws IOException {
  return JBBPOut.BeginBin(JBBPByteOrder.LITTLE_ENDIAN)
      .Byte(z80header.reg_ir)
      .Short(z80header.reg_hl_alt)
      .Short(z80header.reg_de_alt)
      .Short(z80header.reg_bc_alt)
      .Short(makePair(z80header.reg_a_alt, z80header.reg_f_alt))
      .Short(z80header.reg_hl)
      .Short(z80header.reg_de)
      .Short(z80header.reg_bc)
      .Short(z80header.reg_iy)
      .Short(z80header.reg_ix)
      .Byte(z80header.iff2 == 0 ? 0 : 4)
      .Byte(z80header.reg_r)
      .Short(makePair(z80header.reg_a, z80header.reg_f))
      .Short(z80header.reg_sp - (pcOnStack ? 2 : 0))
      .Byte(z80header.emulFlags.interruptmode)
      .Byte(z80header.flags.bordercolor)
      .End()
      .toByteArray();
}
 
Example #9
Source File: JBBPToJavaConverter.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
private void printBitField(final boolean array,
                           final int fieldOrder,
                           final JBBPByteOrder byteOrder,
                           final JBBPNamedFieldInfo nullableFieldInfo,
                           final String sizeOfFieldOut,
                           final JavaSrcTextBuffer buffer,
                           final String modifier,
                           final String type,
                           final String name) {
  if (this.builder.addBinAnnotations) {
    final String binName = nullableFieldInfo == null ? null : nullableFieldInfo.getFieldName();
    if (binName == null) {
      buffer.printf("@Bin(type=BinType.%s,bitNumber=%s,byteOrder=JBBPByteOrder.%s,order=%s)%n",
          (array ? BinType.BIT_ARRAY : BinType.BIT).name(),
          sizeOfFieldOut, byteOrder.name(),
          Integer.toString(fieldOrder));
    } else {
      buffer.printf("@Bin(name=\"%s\",type=BinType.%s,bitNumber=%s,byteOrder=JBBPByteOrder.%s,order=%s)%n",
          binName,
          (array ? BinType.BIT_ARRAY : BinType.BIT).name(),
          sizeOfFieldOut, byteOrder.name(),
          Integer.toString(fieldOrder));
    }
  }
  buffer.printf("%s %s %s;%n", modifier, type, name);
}
 
Example #10
Source File: JBBPDslBuilderTest.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnotatedClass_AnnottatedButWithoutType() {
  class Test {
    @Bin(order = 1)
    int a;
    @Bin(order = 3)
    int c;
    @Bin(order = 2, byteOrder = JBBPByteOrder.LITTLE_ENDIAN)
    int b;
    @Bin(order = 4, arraySizeExpr = "a+b")
    Internal[] d;

    class Internal {
      @Bin(order = 1)
      short a;
      @Bin(order = 2, arraySizeExpr = "8")
      short[] b;
    }
  }

  assertEquals("Test{int a;<int b;int c;d[a+b]{short a;short[8] b;}}", Begin().AnnotatedClass(Test.class).End());
}
 
Example #11
Source File: TapeFileReader.java    From zxpoly with GNU General Public License v3.0 5 votes vote down vote up
public synchronized byte[] getAsWAV() throws IOException {
  final int FREQ = 22050;
  final int CYCLESPERSAMPLE = (int) ((1000000000L / (long) FREQ) / 286L);

  final ByteArrayOutputStream data = new ByteArrayOutputStream(1024 * 1024);

  rewindToStart();
  this.signalInState = false;
  this.counterMain = -1L;
  this.state = State.INBETWEEN;

  while (this.state != State.STOPPED) {
    data.write(this.signalInState ? 0xFF : 0x00);
    updateForSpentMachineCycles(CYCLESPERSAMPLE);
  }

  final JBBPOut out = BeginBin(JBBPByteOrder.LITTLE_ENDIAN);

  return out.
      Byte("RIFF").
      Int(data.size() + 40).
      Byte("WAVE").
      Byte("fmt ").
      Int(16). // Size
      Short(1). // Audio format
      Short(1). // Num channels
      Int(FREQ).// Sample rate
      Int(FREQ). // Byte rate
      Short(1). // Block align
      Short(8). // Bits per sample
      Byte("data").
      Int(data.size()).
      Byte(data.toByteArray()).End().toByteArray();
}
 
Example #12
Source File: SCLPlugin.java    From zxpoly with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ReadResult readFrom(final File file, final int index) throws IOException {
  final List<SCLCatalogItem> list = new ArrayList<>();
  final JBBPBitInputStream in = new JBBPBitInputStream(new FileInputStream(file));
  try {
    final long id = in.readLong(JBBPByteOrder.BIG_ENDIAN);
    if (id == 0x53494E434C414952L) {
      // it's scl
      final int fileNumber = in.readByte();
      for (int i = 0; i < fileNumber; i++) {
        final SCLCatalogItem item = CATALOG_PARSER.parse(in).mapTo(new SCLCatalogItem());
        list.add(item);
      }

      final SCLCatalogItem itemToRead = list.get(index);

      for (int i = 0; i < index; i++) {
        final int len = list.get(i).sectors * 256;
        if (len != in.skip(len)) {
          throw new IllegalStateException("Can't skip bytes:" + list.get(i).length);
        }
      }
      final long offset = in.getCounter();
      return new ReadResult(new ZXPolyData(
          new Info(itemToRead.name, itemToRead.type, itemToRead.start, itemToRead.length,
              (int) offset), this, in.readByteArray(itemToRead.sectors * 256)), null);

    } else {
      throw new IllegalArgumentException("It's not a SCl file: " + file);
    }
  } finally {
    JBBPUtils.closeQuietly(in);
  }
}
 
Example #13
Source File: Spec256AGifEncoder.java    From zxpoly with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void saveFrame(final int[] rgbPixels) throws IOException {
  this.stream.write('!');
  this.stream.write(0xF9);
  this.stream.write(0x04);
  this.stream.write(0);
  this.stream.writeShort(this.frameDelay, JBBPByteOrder.LITTLE_ENDIAN);
  this.stream.write(0);
  this.stream.write(0);

  this.stream.write(',');
  this.stream.writeShort(0, JBBPByteOrder.LITTLE_ENDIAN); // L
  this.stream.writeShort(0, JBBPByteOrder.LITTLE_ENDIAN); // T
  this.stream.writeShort(VideoController.SCREEN_WIDTH, JBBPByteOrder.LITTLE_ENDIAN); // W
  this.stream.writeShort(VideoController.SCREEN_HEIGHT, JBBPByteOrder.LITTLE_ENDIAN); // H
  this.stream.write(0); // flag

  for (int i = 0; i < VideoController.SCREEN_WIDTH * VideoController.SCREEN_HEIGHT; i++) {
    final int ci = VideoController.spec256rgbColorToIndex(rgbPixels[i]);
    if (ci < 0) {
      throw new IOException("Detected unsupported color in buffer [" + Integer.toHexString(rgbPixels[i]) + ']');
    }
    this.indexBuffer[i] = (byte) ci;
  }
  this.stream.write(8);
  Spec256AGifEncoder.compress(this.stream, 8, this.indexBuffer, this.dataBuffer256);
  this.stream.write(0);
}
 
Example #14
Source File: ZxPolyAGifEncoder.java    From zxpoly with GNU General Public License v3.0 5 votes vote down vote up
public ZxPolyAGifEncoder(final File file, final int frameRate, final boolean loop) throws IOException {
  this.stream = new JBBPBitOutputStream(new BufferedOutputStream(new FileOutputStream(file), 0xFFFF));
  this.intsBetweenFrames = (int) (1000 / MainForm.TIMER_INT_DELAY_MILLISECONDS) / frameRate;
  this.frameDelay = (int) (this.intsBetweenFrames * MainForm.TIMER_INT_DELAY_MILLISECONDS) / 10;

  this.stream.write(new byte[] {0x47, 0x49, 0x46, 0x38, 0x39, 0x61});
  this.stream.writeShort(VideoController.SCREEN_WIDTH, JBBPByteOrder.LITTLE_ENDIAN);
  this.stream.writeShort(VideoController.SCREEN_HEIGHT, JBBPByteOrder.LITTLE_ENDIAN);

  this.stream.writeBits(3, JBBPBitNumber.BITS_3);
  this.stream.writeBits(0, JBBPBitNumber.BITS_1);
  this.stream.writeBits(7, JBBPBitNumber.BITS_3);
  this.stream.writeBits(1, JBBPBitNumber.BITS_1);
  this.stream.write(0);
  this.stream.write(0);

  for (final int i : VideoController.PALETTE_ZXPOLY) {
    final int r = (i >>> 16) & 0xFF;
    final int g = (i >>> 8) & 0xFF;
    final int b = i & 0xFF;
    this.stream.write(r);
    this.stream.write(g);
    this.stream.write(b);
  }

  if (loop) {
    this.stream.write('!');
    this.stream.write(0xFF);
    this.stream.write(0x0B);
    this.stream.write(new byte[] {0x4E, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2E, 0x30});
    this.stream.write(3);
    this.stream.write(1);
    this.stream.writeShort(0, JBBPByteOrder.LITTLE_ENDIAN);
    this.stream.write(0);
  }
}
 
Example #15
Source File: Spec256AGifEncoder.java    From zxpoly with GNU General Public License v3.0 5 votes vote down vote up
public Spec256AGifEncoder(final File file, final int frameRate, final boolean loop) throws IOException {
  this.stream = new JBBPBitOutputStream(new BufferedOutputStream(new FileOutputStream(file), 0xFFFF));
  this.intsBetweenFrames = (int) (1000 / MainForm.TIMER_INT_DELAY_MILLISECONDS) / frameRate;
  this.frameDelay = (int) (this.intsBetweenFrames * MainForm.TIMER_INT_DELAY_MILLISECONDS) / 10;

  this.stream.write(new byte[] {0x47, 0x49, 0x46, 0x38, 0x39, 0x61});
  this.stream.writeShort(VideoController.SCREEN_WIDTH, JBBPByteOrder.LITTLE_ENDIAN);
  this.stream.writeShort(VideoController.SCREEN_HEIGHT, JBBPByteOrder.LITTLE_ENDIAN);

  this.stream.writeBits(7, JBBPBitNumber.BITS_3);
  this.stream.writeBits(0, JBBPBitNumber.BITS_1);
  this.stream.writeBits(7, JBBPBitNumber.BITS_3);
  this.stream.writeBits(1, JBBPBitNumber.BITS_1);
  this.stream.write(0);
  this.stream.write(0);

  for (final int i : VideoController.PALETTE_SPEC256) {
    final int r = (i >>> 16) & 0xFF;
    final int g = (i >>> 8) & 0xFF;
    final int b = i & 0xFF;
    this.stream.write(r);
    this.stream.write(g);
    this.stream.write(b);
  }

  if (loop) {
    this.stream.write('!');
    this.stream.write(0xFF);
    this.stream.write(0x0B);
    this.stream.write(new byte[] {0x4E, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2E, 0x30});
    this.stream.write(3);
    this.stream.write(1);
    this.stream.writeShort(0, JBBPByteOrder.LITTLE_ENDIAN);
    this.stream.write(0);
  }
}
 
Example #16
Source File: ZxPolyAGifEncoder.java    From zxpoly with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void saveFrame(final int[] rgbPixels) throws IOException {
  this.stream.write('!');
  this.stream.write(0xF9);
  this.stream.write(0x04);
  this.stream.write(0);
  this.stream.writeShort(this.frameDelay, JBBPByteOrder.LITTLE_ENDIAN);
  this.stream.write(0);
  this.stream.write(0);

  this.stream.write(',');
  this.stream.writeShort(0, JBBPByteOrder.LITTLE_ENDIAN); // L
  this.stream.writeShort(0, JBBPByteOrder.LITTLE_ENDIAN); // T
  this.stream.writeShort(VideoController.SCREEN_WIDTH, JBBPByteOrder.LITTLE_ENDIAN); // W
  this.stream.writeShort(VideoController.SCREEN_HEIGHT, JBBPByteOrder.LITTLE_ENDIAN); // H
  this.stream.write(0); // flag

  for (int i = 0; i < VideoController.SCREEN_WIDTH * VideoController.SCREEN_HEIGHT; i++) {
    final int ci = VideoController.preciseRgbColorToIndex(rgbPixels[i]);
    if (ci < 0) {
      throw new IOException("Detected unsupported color in buffer [" + Integer.toHexString(rgbPixels[i]) + ']');
    }
    this.indexBuffer[i] = (byte) ci;
  }
  this.stream.write(4);
  ZxPolyAGifEncoder.compress(this.stream, 4, this.indexBuffer, this.dataBuffer256);
  this.stream.write(0);

}
 
Example #17
Source File: JBBPFieldTypeParameterContainerTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructorAndGetters() {
  final String name = "name";
  final String extra = "extra";
  final JBBPFieldTypeParameterContainer params = new JBBPFieldTypeParameterContainer(JBBPByteOrder.BIG_ENDIAN, name, extra);
  assertSame(name, params.getTypeName());
  assertSame(extra, params.getExtraData());
  assertEquals(JBBPByteOrder.BIG_ENDIAN, params.getByteOrder());
}
 
Example #18
Source File: VarCustomImpl.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Override
public JBBPAbstractArrayField<? extends JBBPAbstractField> readVarArray(Object sourceStruct, JBBPBitInputStream inStream, JBBPByteOrder byteOrder, JBBPNamedFieldInfo nullableNamedFieldInfo, int extraValue, boolean readWholeStream, int arraySize) throws IOException {
  if (readWholeStream) {
    return new JBBPFieldArrayLong(nullableNamedFieldInfo, inStream.readLongArray(-1, byteOrder));
  } else {
    return new JBBPFieldArrayLong(nullableNamedFieldInfo, inStream.readLongArray(arraySize, byteOrder));
  }
}
 
Example #19
Source File: SZEPlugin.java    From zxpoly with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ReadResult readFrom(final File file, final int index) throws IOException {
  try (FileInputStream inStream = new FileInputStream(file)) {
    final ZXPolyData zxpolyData =
        new ZXPolyData(inStream, this.context.getComponents(AbstractFilePlugin.class));
    final JBBPBitInputStream in = new JBBPBitInputStream(inStream);
    final int length = in.readInt(JBBPByteOrder.BIG_ENDIAN);
    return new ReadResult(zxpolyData, new SessionData(in));
  }
}
 
Example #20
Source File: Info.java    From zxpoly with GNU General Public License v3.0 5 votes vote down vote up
public Info(final InputStream in) throws IOException {
  final JBBPBitInputStream bitin = new JBBPBitInputStream(in);
  this.name = new String(bitin.readByteArray(bitin.readByte()), StandardCharsets.US_ASCII);
  this.type = (char) bitin.readUnsignedShort(JBBPByteOrder.BIG_ENDIAN);
  this.startAddress = bitin.readInt(JBBPByteOrder.BIG_ENDIAN);
  this.length = bitin.readInt(JBBPByteOrder.BIG_ENDIAN);
  this.offset = bitin.readInt(JBBPByteOrder.BIG_ENDIAN);

  this.extra = bitin.readByteArray(bitin.readInt(JBBPByteOrder.BIG_ENDIAN));
}
 
Example #21
Source File: VarCustomImpl.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Override
public void writeVarArray(Object sourceStruct, JBBPAbstractArrayField<? extends JBBPAbstractField> array, JBBPBitOutputStream outStream, JBBPByteOrder byteOrder, JBBPNamedFieldInfo nullableNamedFieldInfo, int extraValue, int arraySizeToWrite) throws IOException {
  final JBBPFieldArrayLong a = (JBBPFieldArrayLong) array;
  if (arraySizeToWrite < 0) {
    for (final long l : a.getArray()) {
      outStream.writeLong(l, byteOrder);
    }
  } else {
    final long[] larr = a.getArray();
    for (int i = 0; i < arraySizeToWrite; i++) {
      outStream.writeLong(larr[i], byteOrder);
    }
  }
}
 
Example #22
Source File: BasedOnQuestionsAndCasesTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
/**
 * Case 03-feb-2020
 * <a href="https://github.com/raydac/java-binary-block-parser/issues/26">Issue #26, Bug in parsing of stringj written in MSB0</a>
 *
 * @throws Exception for any error
 */
@Test
public void testStringMsb0() throws Exception {
  JBBPOut joparam = JBBPOut.BeginBin(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).String("zzzz").Int(12345);
  final byte[] array = joparam.End().toByteArray();
  assertArrayEquals(new byte[] {32, 94, 94, 94, 94, 0, 0, 0x0C, (byte) 0x9C}, array);
  final JBBPFieldStruct bitflds = JBBPParser.prepare("stringj fin; int i;", JBBPBitOrder.MSB0).parse(array);
  assertEquals("zzzz", bitflds.findFieldForNameAndType("fin", JBBPFieldString.class).getAsString());
  assertEquals(12345, bitflds.findFieldForNameAndType("i", JBBPFieldInt.class).getAsInt());
}
 
Example #23
Source File: JBBPToJavaConverter.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Override
public void visitValField(
    final int offsetInCompiledBlock,
    final JBBPByteOrder byteOrder,
    final JBBPNamedFieldInfo nameFieldInfo,
    final JBBPIntegerValueEvaluator expression
) {
  final String fieldName = prepFldName(nameFieldInfo.getFieldName());
  FieldType type = FieldType.VAL;

  registerNamedField(nameFieldInfo, type);

  final String fieldModifier = makeModifier(nameFieldInfo);
  processSkipRemainingFlag();

  final String textFieldType = type.asJavaSingleFieldType();
  if (this.builder.generateFields) {
    if (this.builder.addBinAnnotations) {
      final String name = nameFieldInfo.getFieldName();
      if (name == null) {
        getCurrentStruct().getFields().printf("@Bin");
      } else {
        getCurrentStruct().getFields().printf("@Bin(name=\"%s\")", nameFieldInfo.getFieldName());
      }
    }
    printField(nameFieldInfo, byteOrder, false, offsetInCompiledBlock, getCurrentStruct().getFields(), FieldType.VAL, fieldModifier, textFieldType, fieldName);
  }

  final String valIn = evaluatorToString(NAME_INPUT_STREAM, offsetInCompiledBlock, expression, this.flagSet, false);
  final String valOut = evaluatorToString(NAME_OUTPUT_STREAM, offsetInCompiledBlock, expression, this.flagSet, false);

  getCurrentStruct().getReadFunc().println(String.format("this.%s = %s;", fieldName, valIn));
  getCurrentStruct().getWriteFunc().println(String.format("this.%s = %s;", fieldName, valOut));

  if (this.builder.addGettersSetters) {
    registerGetterSetter(textFieldType, fieldName, true);
  }
}
 
Example #24
Source File: JBBPToJavaConverter.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
private void printField(final JBBPNamedFieldInfo nullableFieldInfo,
                        final JBBPByteOrder byteOrder,
                        final boolean array,
                        final int fieldOrder,
                        final JavaSrcTextBuffer buffer,
                        final FieldType nullableFieldType,
                        final String modifier,
                        final String type,
                        final String name) {
  if (this.builder.addBinAnnotations) {
    final String binName = nullableFieldInfo == null ? null : nullableFieldInfo.getFieldName();

    if (nullableFieldType == null
        || nullableFieldType.getBinType() == BinType.UNDEFINED
        || nullableFieldType.getBinTypeArray() == BinType.UNDEFINED) {
      if (binName == null) {
        buffer.printf("@Bin(byteOrder=JBBPByteOrder.%s,order=%s)%n", byteOrder.name(), Integer.toString(fieldOrder));
      } else {
        buffer.printf("@Bin(name=\"%s\",byteOrder=JBBPByteOrder.%s,order=%s)%n", binName, byteOrder.name(), Integer.toString(fieldOrder));
      }
    } else {
      if (binName == null) {
        buffer.printf("@Bin(type=BinType.%s,byteOrder=JBBPByteOrder.%s,order=%s)%n", array ? nullableFieldType.getBinTypeArray() : nullableFieldType.getBinType(), byteOrder.name(), Integer.toString(fieldOrder));
      } else {
        buffer.printf("@Bin(name=\"%s\",type=BinType.%s,byteOrder=JBBPByteOrder.%s,order=%s)%n", binName, array ? nullableFieldType.getBinTypeArray() : nullableFieldType.getBinType(), byteOrder.name(), Integer.toString(fieldOrder));
      }
    }
  }
  buffer.printf("%s %s %s;%n", modifier, type, name);
}
 
Example #25
Source File: CustomThreeByteIntegerTypeTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
private static int readThreeBytesAsInt(final JBBPBitInputStream in, final JBBPByteOrder byteOrder, final JBBPBitOrder bitOrder) throws IOException {
  final int b0 = in.readByte();
  final int b1 = in.readByte();
  final int b2 = in.readByte();

  final int value = byteOrder == JBBPByteOrder.BIG_ENDIAN ? (b0 << 16) | (b1 << 8) | b2 : (b2 << 16) | (b1 << 8) | b0;

  return bitOrder == JBBPBitOrder.LSB0 ? value : ((int) JBBPFieldInt.reverseBits(value) >>> 8);
}
 
Example #26
Source File: PackedBCDCustomFieldTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isAllowed(final JBBPFieldTypeParameterContainer fieldType, final String fieldName, final int extraData, final boolean isArray) {
  if (fieldType.getByteOrder() == JBBPByteOrder.LITTLE_ENDIAN) {
    System.err.println("Packed Decimal does not support little endian...using big endian instead");
    return false;
  }

  return extraData > 0 && extraData < 15;
}
 
Example #27
Source File: S1Packet.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public TAUnit getTA() {
	try {
		JBBPBitInputStream taStream = new JBBPBitInputStream(new ByteArrayInputStream(data));
		int unit=taStream.readInt(JBBPByteOrder.BIG_ENDIAN);
		int talength = taStream.readInt(JBBPByteOrder.BIG_ENDIAN);
		TAUnit u = new TAUnit(unit, taStream.readByteArray(talength));
		taStream.close();
		return u;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #28
Source File: SinParser.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public void parseHash(JBBPBitInputStream sinStream) throws IOException {
 JBBPParser hashBlocksV2 = JBBPParser.prepare(
           "block[_] {int offset;"
                   + "int length;"
                   + "byte hashLen;"
                   + "byte[hashLen] crc;}"
 );
 if (hashLen>0) {
  byte[] hashBlocks = sinStream.readByteArray(hashLen);
  blocks = hashBlocksV2.parse(hashBlocks).mapTo(new org.sinfile.parsers.v2.HashBlocks());
  certLen = sinStream.readInt(JBBPByteOrder.BIG_ENDIAN);
  cert = sinStream.readByteArray(certLen);
  if (blocks.block.length==1 && blocks.block[0].offset!=0) blocks.block[0].offset=0;
  if (blocks.block[0].length==16) {
	  partitioninfo = sinStream.readByteArray(16);
	  JBBPParser partInfo = JBBPParser.prepare(
	            "<int mot1;"
	          + "<int mot2;"
	          + "<int offset;"
	          + "<int blockcount;"
	  );
	  parti = partInfo.parse(partitioninfo).mapTo(new org.sinfile.parsers.v1.PartitionInfo());
	  if (blocks.block.length>1)
		  dataSize=parti.blockcount*blocks.block[1].length;
  }
  blocks.setSpare(this.payloadType);
 }
 dataType=getDataTypePriv();
}
 
Example #29
Source File: JBBPTextWriterTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructor_OnlyWriter() {
  final Writer someWriter = new StringWriter();
  final JBBPTextWriter writer = new JBBPTextWriter(someWriter);
  assertSame(someWriter, writer.getWrappedWriter());
  assertEquals(JBBPByteOrder.BIG_ENDIAN, writer.getByteOrder());
}
 
Example #30
Source File: JBBPTextWriterTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testByteOrder() throws Exception {
  final JBBPTextWriter writer = makeWriter();

  writer.ByteOrder(JBBPByteOrder.LITTLE_ENDIAN);
  assertEquals(JBBPByteOrder.LITTLE_ENDIAN, writer.getByteOrder());
  writer.ByteOrder(JBBPByteOrder.BIG_ENDIAN);
  assertEquals(JBBPByteOrder.BIG_ENDIAN, writer.getByteOrder());
}