convert.dart 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import 'dart:typed_data';
  2. class Convert {
  3. // String (Dart uses UTF-16) to bytes
  4. static stringToUint8(String string) async {
  5. var list = new List<int>();
  6. string.runes.forEach((rune) {
  7. if (rune >= 0x10000) {
  8. rune -= 0x10000;
  9. int firstWord = (rune >> 10) + 0xD800;
  10. list.add(firstWord >> 8);
  11. list.add(firstWord & 0xFF);
  12. int secondWord = (rune & 0x3FF) + 0xDC00;
  13. list.add(secondWord >> 8);
  14. list.add(secondWord & 0xFF);
  15. } else {
  16. list.add(rune >> 8);
  17. list.add(rune & 0xFF);
  18. }
  19. });
  20. Uint8List bytes = Uint8List.fromList(list);
  21. return bytes;
  22. }
  23. // Bytes to UTF-16 string
  24. static uint8ToString(Uint8List bytes) async {
  25. StringBuffer buffer = new StringBuffer();
  26. for (int i = 0; i < bytes.length;) {
  27. int firstWord = (bytes[i] << 8) + bytes[i + 1];
  28. if (0xD800 <= firstWord && firstWord <= 0xDBFF) {
  29. int secondWord = (bytes[i + 2] << 8) + bytes[i + 3];
  30. buffer.writeCharCode(
  31. ((firstWord - 0xD800) << 10) + (secondWord - 0xDC00) + 0x10000);
  32. i += 4;
  33. } else {
  34. buffer.writeCharCode(firstWord);
  35. i += 2;
  36. }
  37. }
  38. return buffer.toString();
  39. }
  40. }