[codec] Problem with the BinaryCodec class

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

[codec] Problem with the BinaryCodec class

t_liang
System.out.println(BinaryCodec.toAsciiString(new byte[] { 'a' })); // output 01100001 System.out.println(BinaryCodec.toAsciiString(new byte[] { 'b' })); // output 01100010 System.out.println(BinaryCodec.toAsciiString(new byte[] { 'a', 'b' })); // output 0110001001100001(ba), why not 0110000101100010(ab)?
Reply | Threaded
Open this post in threaded view
|

Re: [codec] Problem with the BinaryCodec class

Alex Herbert
Hi,

This is functioning as expected. The input array of bytes is interpreted in
little-endian order. The first byte in the input array is the smallest part
of the output binary string interpreted as a binary number. So if you pass
two bytes the output string will start with the second byte and end with
the first byte when reading left to right.

You can see how this works by looking at the test for the method here:

https://gitbox.apache.org/repos/asf?p=commons-codec.git;a=blob;f=src/test/java/org/apache/commons/codec/binary/BinaryCodecTest.java;h=2e3e6380bcc08d913f514deaebbdfa3a325600ed;hb=HEAD#l296

As you set more bits in each byte (filling from the lowest bit first) the
output string fills up from the right.

The output order is a format for data transfer. The key point is that the
output string will be correctly converted back to the original bytes using
the complementary BinaryCodec.fromAscii method.

Regards,

Alex


On Thu, 4 Mar 2021 at 14:20, t_liang <[hidden email]> wrote:

> System.out.println(BinaryCodec.toAsciiString(new byte[] { 'a' })); //
> output 01100001 System.out.println(BinaryCodec.toAsciiString(new byte[] {
> 'b' })); // output 01100010
> System.out.println(BinaryCodec.toAsciiString(new byte[] { 'a', 'b' })); //
> output 0110001001100001(ba), why not 0110000101100010(ab)?