How to write a binary literal in Dart
Asked Answered
Q

4

5

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.

Quinine answered 29/7, 2020 at 19:4 Comment(1)
It's not supported in dart. See this Github issueColombes
V
10

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);.

Vincenty answered 30/7, 2020 at 7:21 Comment(0)
P
5

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
Persse answered 5/1, 2023 at 2:40 Comment(0)
C
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/

Communicable answered 17/5, 2022 at 14:19 Comment(0)
I
0

Simple workaround using extensions

void main() {
  print(1110111.b); //prints 119
}

extension Binary on int {
  int get b {
    return int.parse(toRadixString(10), radix: 2);
  }
}
Indeciduous answered 18/9 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.