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?
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();
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With