3

How do you write a Binary Literal in Dart?

I can write a Hex Literal like so:

Int Number = 0xc

If I try the conventional way to write a Binary Literal:

Int Number = 0b1100

I get an error. I've tried to look it up, but I've not been able to find any information other than for hex.

maglax
  • 31
  • 1
  • 2

3 Answers3

8

There are currently no built-in binary number literals in Dart (or any base other than 10 and 16).

The closest you can get is: var number = int.parse("1100", radix: 2);.

lrn
  • 64,680
  • 7
  • 105
  • 121
3

Maybe you can use this:

// 0b1100 -> 1 at 3th bit and 1 at 2nd bit
final number = 1 << 3 | 1 << 2;

// Print binary string
print(number.toRadixString(2)) // 1100
Luis Ciber
  • 181
  • 6
0

Try binary package:

import 'package:binary/binary.dart';

void main() {
  // New API.S
  print(0x0C.toBinaryPadded(8)); // 00001100
}

see: https://pub.dev/documentation/binary/latest/