cryptocoinjs/bigi — pull request #7 by dcousens (2014-05-11 07:18:19+00:00)
Title: Convert cleanup and bug fixes

This pull request cleans up `convert.js`, reworks the implementations of `BigInteger.toBuffer` and `BigInteger.toHex`, and removes the custom implementation of `toByteArraySigned`.
It also removed a subtle bug in `BigInteger.toByteArrayUnsigned` which was taking the absolute value of the `BigInteger`, and then giving the big-endian byte array for that.
This has been resolved so that `-1` resolves to `255` and so on.

Finally, (correct me if I'm wrong) it is my interpretation that `BigInteger.toByteArraySigned` was attempting to reproduce the behaviour of a typical [DER integer](http://luca.ntop.org/Teaching/Appunti/asn1.html) (also see this answer on [crypto.stackexchange](https://crypto.stackexchange.com/questions/12488/can-r-and-s-from-an-ecdsa-signature-be-negative-numbers)).
If that assumption is correct, than the `toByteArraySigned()` implementation was incorrect in that it was appending a `0x80` to the front of a negative integer.

>DER-encoded integers are defined this way:
> * Positive values are represented by the minimal number of bytes that can represent the integer (in bigendian byte order), with the msbit of the initial byte being clear.
> * For example, the value 32768 would be represented by the three bytes 0x00 0x80 0x00. We are not allowed to use the two octets 0x80 0x00, because 0x80 has the msbit set
> * Negative values are represented by the minimal number of bytes that can represent the integer (in two's complement notation), with the msbit of the initial byte being set.
> * Zero is represented as a single 0x00 byte

It should also be noted, that `BigInteger.toByteArray` already gives a DER encoded integer, and as such a custom implementation was unnecessary.
I have added tests to enforce this behaviour using the slightly modified test data in the documentation previous above `BigInteger.toByteArraySigned`.