Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to binary

Tags:

dart

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?

like image 282
H.R. Avatar asked Dec 03 '22 18:12

H.R.


2 Answers

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();
like image 191
lrn Avatar answered Jan 09 '23 20:01

lrn


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.

  • https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.String#id_codeUnitAt
  • https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.String#id_codeUnits

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)
like image 34
Michael Fenwick Avatar answered Jan 09 '23 21:01

Michael Fenwick