H.R.
H.R.

Reputation: 506

How to convert string to binary

Hey is there a dart build in way of converting a string to eg a binarystring print("a".toBinary()) => 0110 0001

or what do you think would be the best way to do so?

Upvotes: 8

Views: 8358

Answers (3)

BrightXO
BrightXO

Reputation: 1

Try the following:

import 'dart:core';

void main() {
    String name = "hello";
    for(int binary in name.codeUnits)print(binary.toRadixString(2));
}

Upvotes: 0

lrn
lrn

Reputation: 71623

You need to say which format you need. Strings are sequences of 16-bit integers. In some settings they are interpreted as UTF-16, where some integers (code units) represent a single code point, other code points require two code units. In yet other settings, a "character" is more than one code point. So, to convert a string to bits, you need to be exact about how you interpret the string.

Here you write only eight bits for an "a", not, e.g., "000000000110001", so I assume you only consider ASCII strings.

Let's assume it's all ASCII, and you want eight-bit results:

var binstring = string.codeUnits.map((x) => x.toRadixString(2).padLeft(8, '0'))
                                .join();

Upvotes: 12

Michael Fenwick
Michael Fenwick

Reputation: 2494

It sounds like you are looking for the Dart equivalents of javascript's String.charCodeAt method. In Dart there are two options depending on whether you want to the character codes for the whole string or just a single character within the string.

String.codeUnitAt is a method that returns an int for the character at a given index in the string. You use it as follows:

String str = 'hello';
print(str.codeUnitAt(3)); //108

You can use String.codeUnits to convert the entire string into their integer values:

String str = 'hello';
print(str.codeUnits); //[104, 101, 108, 108, 111]

If you need to then convert those integers into their corresponding binary strings you'll want to us int.toRadixString with an argument of 2

String str = 'hello';
List<String> binarys = str.codeUnits.map((int strInt) => strInt.toRadixString(2));
print(binarys); //(1101000, 1100101, 1101100, 1101100, 1101111)

Upvotes: 8

Related Questions