Trafalgar
Trafalgar

Reputation: 145

There's something wrong in converting decimal to binary

int main(){
    int input;
    int bin = 0, i = 1;
    print("Please input a number");
    input = num.parse(stdin.readLineSync());
    while(input > 0)
    {
        bin = bin + (input % 2)*i;
        input = input/2;
        i = i * 10;
    }


    return 0;
}

It returned infinite numbers.

Upvotes: 3

Views: 4070

Answers (5)

(Using DART and Flutter) You can do that using a native method called toRadixString. I think is better considering performance and reliability.

BigInt toBinary(int input) {
  return BigInt.parse(input.toRadixString(2));
}

Your code will be then

int main(){
    int input;
    int bin = 0, i = 1;
    print("Please input a number");
    input = num.parse(stdin.readLineSync());
    return input.toRadixString(2);
}

Upvotes: 0

Junaid Hassan Final
Junaid Hassan Final

Reputation: 365

//number is always in int
static String decimalToBinary(int number) {
  return number.toRadixString(2);
}

//binary is always in string
static int binaryToDecimal(String binary) {
  return int.parse(binary, radix: 2);
}

Upvotes: 0

a.l.e
a.l.e

Reputation: 868

Here is a version of the above function that:

  • uses the integer division
  • with a ternary conditional operator, avoids the conversion to string.
  • sets the most significant bit to the left (bin = (dec % 2) + bin; which is what most people expects, but is not what the original snippet did)
String dec2bin(int dec) {
  var bin = '';
  while (dec > 0) {
    bin = (dec % 2 == 0 ? '0' : '1') + bin;
    dec ~/= 2;
  }
  return bin;
}

P.S: But, of course, one can simply write:

var bin = num.toRadixString(2);

There is no real need to write your own dec2bin function.

Upvotes: 5

Cassio Seffrin
Cassio Seffrin

Reputation: 8580

As the int result can become easily big in length and the max int value in dart is 2e53 (and much less if you compile to web). it's better to change the approach and return as a String.

  String dec2bin(int decimal) {
    String bin = '';
    while (decimal > 0) {
      bin = bin + (decimal % 2).toString();
      decimal = (decimal / 2).floor();
    }
    return bin;
  }

   print(dec2bin(132070242815));

Result: 1111111110011111111111111111110101111

Upvotes: 0

Sandeep
Sandeep

Reputation: 106

You just need to take care of double to int conversion: input = (input/2).floor()

See this working code:

void main() {
  int input;
  int bin = 0, i = 1;
  input = 5;
  while(input > 0)
  {
      bin = bin + (input % 2)*i;
      input = (input/2).floor();
      i = i * 10;
  }

  print(bin);
}

Upvotes: 5

Related Questions