Edited to add some clarification and comments to code
First you have to define a map from String
to BigInt
. In other word, you have to use an encoding scheme to encode characters to numbers. The String
class in dart provides a getter codeUnits
to convert a string to a List
of UTF-16 code of characters, thus if you want to adopt the UTF-16 encoding, you can take advantage of this getter method, and you can turn the list back to string with the factory constructor fromCharCodes
of String
:
BigInt uint16SeqToBigInt(List<int> seq){
var ret = BigInt.from(0);
int offset = 0;
for(int i in seq){
// Shift the UTF-16 code of each character to "slots" of 16-bit size
ret += (BigInt.from(i)) << offset;
offset += 16;
}
return ret;
}
List<int> bigIntToUint16Seq(BigInt val){
final ret = <int>[];
int cur;
while(true){
// 0xFFFF is a bit mask to extract the lower 16-bit value from val
cur = (val & BigInt.from(0xFFFF)).toInt();
if(cur != 0){
ret.add(cur);
// The last 16 bits is interpreted, now discard them
val = val >> 16;
}else{
break;
}
}
return ret;
}
void main() {
String original = "this is a simple string";
final utf16BigInt = uint16SeqToBigInt(original.codeUnits);
final decoded = String.fromCharCodes(bigIntToUint16Seq(utf16BigInt));
print(decoded);
// "this is a simple string"
}