Skip to content

How to parse bits #46

Closed
Closed
@Gerschtli

Description

@Gerschtli

Hey,

I played around with you library and wanted to figure out how I can parse a sequence like one byte, then 3 bits and then one byte with Big Endian mode.

I created the following JBBP script:

byte byte1;
bit:3 bits;
byte byte2;

which generated

package org.jbbp;

import com.igormaznitsa.jbbp.model.*;
import com.igormaznitsa.jbbp.io.*;
import com.igormaznitsa.jbbp.compiler.*;
import com.igormaznitsa.jbbp.compiler.tokenizer.*;
import java.io.IOException;
import java.util.*;

/**
 * Generated from JBBP script by internal JBBP Class Source Generator
 */
public class Example {
	
	/**
	 * The Constant contains parser flags
	 * @see JBBPParser#FLAG_SKIP_REMAINING_FIELDS_IF_EOF
	 * @see JBBPParser#FLAG_NEGATIVE_EXPRESSION_RESULT_AS_ZERO
	 */
	protected static final int _ParserFlags_ = 0;

	public byte byte1;
	public byte bits;
	public byte byte2;
	

	public Example () {
	}

	public Example read(final JBBPBitInputStream In) throws IOException {
		this.byte1 = (byte)In.readByte();
		this.bits = In.readBitField(JBBPBitNumber.BITS_3);
		this.byte2 = (byte)In.readByte();
		
		return this;
	}

	public Example write(final JBBPBitOutputStream Out) throws IOException {
		Out.write(this.byte1);
		Out.writeBits(this.bits,JBBPBitNumber.BITS_3);
		Out.write(this.byte2);
		
		return this;
	}
}

To test this, I used this data: 0x01a100

Binary representation:
00000001 101 00001000 00000
________ ___ ________
 ^        ^    ^ 
 |        |    byte2
 |        bits
 byte1

I want to get

byte1: 1
bits:  5
byte2: 8

but get

byte1: 1
bits:  1
byte2: 20

I used this JUnit Test:

package org.example;

import static org.assertj.core.api.Assertions.assertThat;

import com.igormaznitsa.jbbp.io.JBBPBitInputStream;
import java.io.ByteArrayInputStream;
import java.util.HexFormat;
import org.jbbp.Example;
import org.junit.jupiter.api.Test;

class ExampleTest {
  @Test
  void test() throws Exception {
    // 00000001 10100001 00000000
    var data = HexFormat.of().parseHex("01a100");

    var example = new Example();
    example.read(new JBBPBitInputStream(new ByteArrayInputStream(data)));

    var expected = new Example();
    expected.byte1 = 1; // 00000001
    expected.bits = 5;  // 00000101
    expected.byte2 = 8; // 00001000

    System.out.println("byte1: " + example.byte1);
    System.out.println("bits:  " + example.bits);
    System.out.println("byte2: " + example.byte2);

    assertThat(example).usingRecursiveComparison().isEqualTo(expected);
  }
}

Can you help me to use your library to reach my expected outcome? Thank you!

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions