--- /dev/null
+package org.apache.poi.ss.formula.functions;\r
+\r
+import org.apache.poi.ss.formula.OperationEvaluationContext;\r
+import org.apache.poi.ss.formula.eval.*;\r
+\r
+/**\r
+ * Implementation for Excel Bin2Dec() function.<p/>\r
+ * <p/>\r
+ * <b>Syntax</b>:<br/> <b>Bin2Dec </b>(<b>number</b>)<br/>\r
+ * <p/>\r
+ * Converts a binary number to decimal.\r
+ * <p/>\r
+ * Number is the binary number you want to convert. Number cannot contain more than 10 characters (10 bits).\r
+ * The most significant bit of number is the sign bit. The remaining 9 bits are magnitude bits.\r
+ * Negative numbers are represented using two's-complement notation.\r
+ * <p/>\r
+ * Remark\r
+ * If number is not a valid binary number, or if number contains more than 10 characters (10 bits),\r
+ * BIN2DEC returns the #NUM! error value.\r
+ *\r
+ * @author cedric dot walter @ gmail dot com\r
+ */\r
+public class Bin2Dec extends Fixed1ArgFunction implements FreeRefFunction {\r
+\r
+ public static final FreeRefFunction instance = new Bin2Dec();\r
+\r
+ public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval numberVE) {\r
+ String number = OperandResolver.coerceValueToString(numberVE);\r
+ if (number.length() > 10) {\r
+ return ErrorEval.NUM_ERROR;\r
+ }\r
+\r
+ String unsigned;\r
+\r
+ //If the leftmost bit is 0 -- number is positive.\r
+ boolean isPositive;\r
+ if (number.length() < 10) {\r
+ unsigned = number;\r
+ isPositive = true;\r
+ } else {\r
+ unsigned = number.substring(1);\r
+ isPositive = number.startsWith("0");\r
+ }\r
+\r
+ String value;\r
+ int sum;\r
+ if (isPositive) {\r
+ //bit9*2^8 + bit8*2^7 + bit7*2^6 + bit6*2^5 + bit5*2^4+ bit3*2^2+ bit2*2^1+ bit1*2^0\r
+ sum = getDecimalValue(unsigned);\r
+ value = String.valueOf(sum);\r
+ } else {\r
+ //The leftmost bit is 1 -- this is negative number\r
+ //Inverse bits [1-9]\r
+ String inverted = toggleBits(unsigned);\r
+ // Calculate decimal number\r
+ sum = getDecimalValue(inverted);\r
+\r
+ //Add 1 to obtained number\r
+ sum++;\r
+\r
+ value = "-" + String.valueOf(sum);\r
+ }\r
+\r
+ return new NumberEval(Long.parseLong(value));\r
+ }\r
+\r
+ private int getDecimalValue(String unsigned) {\r
+ int sum = 0;\r
+ int numBits = unsigned.length();\r
+ int power = numBits - 1;\r
+\r
+ for (int i = 0; i < numBits; i++) {\r
+ int bit = Integer.parseInt(unsigned.substring(i, i + 1));\r
+ int term = (int) (bit * Math.pow(2, power));\r
+ sum += term;\r
+ power--;\r
+ }\r
+ return sum;\r
+ }\r
+\r
+ private static String toggleBits(String s) {\r
+ long i = Long.parseLong(s, 2);\r
+ long i2 = i ^ ((1L << s.length()) - 1);\r
+ String s2 = Long.toBinaryString(i2);\r
+ while (s2.length() < s.length()) s2 = '0' + s2;\r
+ return s2;\r
+ }\r
+\r
+ public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) {\r
+ if (args.length != 1) {\r
+ return ErrorEval.VALUE_INVALID;\r
+ }\r
+ return evaluate(ec.getRowIndex(), ec.getColumnIndex(), args[0]);\r
+ }\r
+}\r