dart 如何将二进制字符串转换为文本字符串,并在flutter中进行反向转换?

evrscar2  于 2023-09-28  发布在  Flutter
关注(0)|答案(1)|浏览(153)

我想做的是输入一个字符串,如["01001000 01100101 01111001"],并将其转换为["Hey"]或相反,输入["Hey"],并将其转换为["01001000 01100101 01111001"]

jm2pwxwz

jm2pwxwz1#

  1. String encode(String value) {
  2. // Map each code unit from the given value to a base-2 representation of this
  3. // code unit, adding zeroes to the left until the string has length 8, and join
  4. // each code unit representation to a single string using spaces
  5. return value.codeUnits.map((v) => v.toRadixString(2).padLeft(8, '0')).join(" ");
  6. }
  7. String decode(String value) {
  8. // Split the given value on spaces, parse each base-2 representation string to
  9. // an integer and return a new string from the corresponding code units
  10. return String.fromCharCodes(value.split(" ").map((v) => int.parse(v, radix: 2)));
  11. }
  12. void main() {
  13. print(encode("Hey")); // Output: 01001000 01100101 01111001
  14. print(decode("01001000 01100101 01111001")); // Output: Hey
  15. }

相关问题