0

If I was to try to make a program that outputs .Flac files in Java, Flac-format, It appears that I would need to output values less than a byte. Is it even possible to output values less than a byte such as a nybble or a 5-bit number?

  • 1
    It's more likely you will need to set 5 bits of a whole byte. The search term you're looking for is "bit mask". – Federico klez Culloca Aug 01 '20 at 10:08
  • See [here](https://stackoverflow.com/questions/30327937/bit-shifting-and-bit-mask-sample-code) for example. – Federico klez Culloca Aug 01 '20 at 10:10
  • I presume you'll have to write bits (represented as bools, for example) and then turn these into bytes. I have a personal utility class (BitAssembler) to which you push bits, and from which you can pop assembled bytes. https://github.com/nylanderdev/nylander-utils Just remember that you need to push 8 bits for each byte you pop, so you'll have to add trailing or leading padding bits yourself. – nylanderDev Aug 01 '20 at 10:18
  • 1
    As you can see the 5 bit number is preceeded by a 3 bit number, which adds up to 8 bits, or one byte. So you'll want to push 3 bits, then 5 bits, and pop the resulting byte. – nylanderDev Aug 01 '20 at 10:24

2 Answers2

1

ImageOutputStream.writeBits should do what you want.

You create an ImageOutputStream using the ImageIO.createImageOutputStream method:

Path flacPath = Paths.get(filename);

try (ImageOutputStream out = ImageIO.createImageOutputStream(
    new BufferedOutputStream(Files.newOutputStream(flacPath)))) {

    out.writeBits(0b1110101011, 10);
    // etc.
}
VGR
  • 40,506
  • 4
  • 48
  • 63
0

In the end I think I can do this using bit shifting and logical commands such as & and | opperators.