Skip to content

Commit

Permalink
ByteUtils: improve JavaDoc comments for bigIntegerToBytes(), bytesToB…
Browse files Browse the repository at this point in the history
…igInteger()
  • Loading branch information
msgilligan authored and schildbach committed Jun 24, 2024
1 parent fae543b commit 0aa17cd
Showing 1 changed file with 12 additions and 13 deletions.
25 changes: 12 additions & 13 deletions core/src/main/java/org/bitcoinj/base/internal/ByteUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,21 +64,20 @@ public static byte[] parseHex(String string) {

/**
* <p>
* The regular {@link BigInteger#toByteArray()} includes the sign bit of the number and
* might result in an extra byte addition. This method removes this extra byte.
* The built-in {@link BigInteger#toByteArray()} includes the sign bit of the number and
* may result in an extra byte in cases of unsigned data. This method removes this extra byte.
* </p>
* <p>
* Assuming only positive numbers, it's possible to discriminate if an extra byte
* is added by checking if the first element of the array is 0 (0000_0000).
* Due to the minimal representation provided by BigInteger, it means that the bit sign
* is the least significant bit 0000_000<b>0</b> .
* Otherwise the representation is not minimal.
* For example, if the sign bit is 0000_00<b>0</b>0, then the representation is not minimal due to the rightmost zero.
* Assuming only positive numbers, it's possible to tell if an extra byte
* was added by checking if the first element of the array is 0 (0000_0000).
* Due to the guarantee of a minimal representation provided by BigInteger, we know that the sign bit
* will be the least significant bit 0000_000<b>0</b> of a zero-value first byte.
* Otherwise the representation would not be minimal.
* </p>
* This is the antagonist to {@link #bytesToBigInteger(byte[])}.
* @param b the integer to format into a byte array
* @param numBytes the desired size of the resulting byte array
* @return numBytes byte long array.
* This is the inverse of {@link #bytesToBigInteger(byte[])}.
* @param b the non-negative integer to format into a byte array
* @param numBytes the maximum allowed size of the resulting byte array
* @return byte array of max length {@code numBytes}
*/
public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) {
checkArgument(b.signum() >= 0, () -> "b must be positive or zero: " + b);
Expand All @@ -95,7 +94,7 @@ public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) {
}

/**
* Converts an array of bytes into a positive BigInteger. This is the antagonist to
* Converts an array of bytes into a positive BigInteger. This is the inverse of
* {@link #bigIntegerToBytes(BigInteger, int)}.
*
* @param bytes to convert into a BigInteger
Expand Down

0 comments on commit 0aa17cd

Please sign in to comment.