Created
March 12, 2011 17:59
-
-
Save bensie/867409 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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