java - Incorrect return on binary to dec converter -
fixing , tidying converter when noticed somehow gives out incorrect conversions.
for example, when creating new number convert using binarynumber bn1 = new binarynumber("1011");
, asking give out result system.out.println(bn1.converttodecimal());
prints out 3 instead of correct result of 11.
i'm sure got actual conversion wrong going through in head can't find mistake.
public class binarynumber { private string n; public binarynumber(string pn) { n = pn; } public string getn() { return n; } // creating .converttodecimal() public int converttodecimal() { int bitposition = 0; int sum = 0; (int = n.length() - 1; >= 0; i--) { sum = sum + (int) math.pow(2, bitposition) * (n.charat(i) - 48); } return sum; } // creating .add add 2 different binary numbers after // converting public int add(binarynumber bn2) { return converttodecimal() + bn2.converttodecimal(); } // creating .sub subtract 2 different binary numbers after // converting public int sub(binarynumber bn2) { return converttodecimal() - bn2.converttodecimal(); } }
you need increment bitposition variable.
int bitposition = 0; int sum = 0;
(int = n.length() - 1; >= 0; i--) { sum = sum + (int) math.pow(2, bitposition++) * (n.charat(i) - 48); } return sum;
Comments
Post a Comment