{

How to convert decimal to/from a binary number in Dart


A binary number is a number based on base 2. It contains either zero or one digit. Each digit is called a bit.

Example binary numbers are 1011.

Numbers with a base of ten, or numbers ranging from 0 to 9, are known as Decimal Numbers. 45 is an example of a decimal number. Learn how to convert decimal to Binary in a dart in this quick tutorial.

How to convert decimal numbers to Binary numbers in Dart?

In this example, a Decimal number with base 10 is converted to a Binary number with base 16 in dart and flutter

decimal numbers are represented using int type in dart. It has the toRadixString() method which accepts the base of an argument.

Number.toRadixString(base)

the base can be 16 for Hexa, 8 for octal, and 2 for binary.

Here is a code for parsing decimal to Binary example.

void main() {
  final decimalNumber = 158;
  final binaryNumber = decimalNumber.toRadixString(2); // 9e
  print(binaryNumber);
}

Output:

10011110

How to parse Binary numbers to decimal numbers in Dart?

This example converts Binary to decimal numbers in dart and flutter.

The int has the parseInt method which takes string number and base

syntax

int.parseInt(String, {radix: base})

The string is a string of Binary numbers to convert. the base is a base such as 2, 8,16, etc.

Here is a code for convert Binary to decimal example

void main() {
  final decimalNumber = 158;
  final binaryNumber = decimalNumber.toRadixString(2);
  print(decimalNumber.runtimeType);
  print(binaryNumber);


  int decimalNumber1 = int.parse('10011110', radix: 2);
  print(decimalNumber1);
}

Output:

int
10011110
158

Conclusion

In a summary, Learned the following examples

  • Convert decimal to Binary number using the toRadixString method
  • Convert Binary to decimal number using parseInt() method
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example