- // If using hex, should always be multiples of 4 bits, which can get
- // out of sync if first number has leading 0 bits, eg 2 in hex is 0010
- // which would show up as 10, thus missing 2 bits it should have.
- if (base.asInt == 16) {
- var firstDigit = parseInt(base.parts[0], 16);
- if (firstDigit >= 4 && firstDigit < 8) {
- binLeadingZeros += "0";
- }
- else if (firstDigit >= 2 && firstDigit < 4) {
- binLeadingZeros += "00";
- }
- else if (firstDigit >= 1 && firstDigit < 2) {
- binLeadingZeros += "000";
- }
+ // If the first integer is small, it must be padded with zeros.
+ // Otherwise the chance of the first bit being 1 is 100%, which is
+ // obviously incorrect.
+ // This is not perfect for unusual bases, eg base 6 has 2.6 bits, so is
+ // slightly biased toward having leading zeros, but it's still better
+ // than ignoring it completely.
+ // TODO: revise this, it seems very fishy. For example, in base 10, there are
+ // 8 opportunities to start with 0 but only 2 to start with 1
+ var firstInt = base.ints[0];
+ var firstIntBits = Math.floor(Math.log2(firstInt))+1;
+ var maxFirstIntBits = Math.floor(Math.log2(base.asInt-1))+1;
+ var missingFirstIntBits = maxFirstIntBits - firstIntBits;
+ var firstIntLeadingZeros = "";
+ for (var i=0; i<missingFirstIntBits; i++) {
+ binLeadingZeros += "0";
+ }
+ // Convert base.ints to BigInteger.
+ // Due to using unusual bases, eg cards of base52, this is not as simple as
+ // using BigInteger.parse()
+ var entropyInt = BigInteger.ZERO;
+ for (var i=base.ints.length-1; i>=0; i--) {
+ var thisInt = BigInteger.parse(base.ints[i]);
+ var power = (base.ints.length - 1) - i;
+ var additionalEntropy = BigInteger.parse(base.asInt).pow(power).multiply(thisInt);
+ entropyInt = entropyInt.add(additionalEntropy);