Skip to content

Instantly share code, notes, and snippets.

@bensie
Created March 12, 2011 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bensie/867409 to your computer and use it in GitHub Desktop.
Save bensie/867409 to your computer and use it in GitHub Desktop.
/**
* Returns a byte array containing the two's-complement
* representation of this BigInteger. The byte array will be in
* <i>big-endian</i> byte-order: the most significant byte is in
* the zeroth element. The array will contain the minimum number
* of bytes required to represent this BigInteger, including at
* least one sign bit, which is <tt>(ceil((this.bitLength() +
* 1)/8))</tt>. (This representation is compatible with the
* {@link #BigInteger(byte[]) (byte[])} constructor.)
*
* @return a byte array containing the two's-complement representation of
* this BigInteger.
* @see #BigInteger(byte[])
*/
public byte[] toByteArray() {
int byteLen = bitLength()/8 + 1;
byte[] byteArray = new byte[byteLen];
for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i>=0; i--) {
if (bytesCopied == 4) {
nextInt = getInt(intIndex++);
bytesCopied = 1;
} else {
nextInt >>>= 8;
bytesCopied++;
}
byteArray[i] = (byte)nextInt;
}
return byteArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment