hexUtils.dart 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import 'dart:convert' show utf8;
  2. import 'dart:typed_data';
  3. import 'package:convert/convert.dart' show hex;
  4. bool isHexPrefixed(String str) {
  5. ArgumentError.checkNotNull(str);
  6. return str.startsWith('0x');
  7. }
  8. /// Is the string a hex string.
  9. bool isHexString(String value, {int length = 0}) {
  10. ArgumentError.checkNotNull(value);
  11. // if (!RegExp('^0x[0-9A-Fa-f]*\$').hasMatch(value)) return false;
  12. if (!RegExp(r'\b(?:0[xX])?[0-9a-fA-F]+\b').hasMatch(value)) return false;
  13. if (length > 0 && value.length != 2 + 2 * length) return false;
  14. return true;
  15. }
  16. String stripHexPrefix(String hexString) {
  17. ArgumentError.checkNotNull(hexString);
  18. if (hexString.startsWith("0x") || hexString.startsWith("0X")) {
  19. return hexString.substring(2);
  20. }
  21. return hexString;
  22. }
  23. String addHexPrefix(String hexString) {
  24. ArgumentError.checkNotNull(hexString);
  25. if (!hexString.startsWith("0x") && !hexString.startsWith("0X")) {
  26. return '0x$hexString';
  27. }
  28. return hexString;
  29. }
  30. /// Pads a [String] to have an even length
  31. String padToEven(String value) {
  32. ArgumentError.checkNotNull(value);
  33. var a = '$value';
  34. if (a.length % 2 == 1) a = '0${a}';
  35. return a;
  36. }
  37. /// Converts a [int] into a hex [String]
  38. String intToHex(i) {
  39. ArgumentError.checkNotNull(i);
  40. return '0x${i.toRadixString(16)}';
  41. }
  42. /// Converts an [int] or [BigInt] to a [Uint8List]
  43. Uint8List intToBuffer(i) {
  44. return Uint8List.fromList(i == null || i == 0 || i == BigInt.zero ? [] : hex.decode(padToEven(intToHex(i).substring(2))));
  45. }
  46. Uint8List stringToBuffer(String i) {
  47. return Uint8List.fromList(i.isEmpty ? [] : hex.decode(padToEven(stripHexPrefix(i))));
  48. }
  49. /// Get the binary size of a string
  50. int getBinarySize(String str) {
  51. ArgumentError.checkNotNull(str);
  52. return utf8.encode(str).length;
  53. }
  54. /// Returns TRUE if the first specified array contains all elements from the second one. FALSE otherwise.
  55. bool arrayContainsArray(List superset, List subset, {bool some = false}) {
  56. ArgumentError.checkNotNull(superset);
  57. ArgumentError.checkNotNull(subset);
  58. if (some) return Set.from(superset).intersection(Set.from(subset)).length > 0;
  59. return Set.from(superset).containsAll(subset);
  60. }
  61. /// Should be called to get utf8 from it's hex representation
  62. String toUtf8(String hexString) {
  63. ArgumentError.checkNotNull(hexString);
  64. List<int> bufferValue = hex.decode(padToEven(stripHexPrefix(hexString).replaceAll(RegExp('^0+|0+\$'), '')));
  65. return utf8.decode(bufferValue);
  66. }
  67. /// Should be called to get ascii from it's hex representation
  68. String toAscii(String hexString) {
  69. ArgumentError.checkNotNull(hexString);
  70. var start = hexString.startsWith(RegExp('^0x')) ? 2 : 0;
  71. return String.fromCharCodes(hex.decode(hexString.substring(start)));
  72. }
  73. /// Should be called to get hex representation (prefixed by 0x) of utf8 string
  74. String fromUtf8(String stringValue) {
  75. ArgumentError.checkNotNull(stringValue);
  76. var stringBuffer = utf8.encode(stringValue);
  77. return "0x${padToEven(hex.encode(stringBuffer)).replaceAll(RegExp('^0+|0+\$'), '')}";
  78. }
  79. /// Should be called to get hex representation (prefixed by 0x) of ascii string
  80. String fromAscii(String stringValue) {
  81. ArgumentError.checkNotNull(stringValue);
  82. var hexString = '';
  83. for (var i = 0; i < stringValue.length; i++) {
  84. var code = stringValue.codeUnitAt(i);
  85. var n = hex.encode([code]);
  86. hexString += n.length < 2 ? '0${n}' : n;
  87. }
  88. return '0x$hexString';
  89. }
  90. Uint8List hexToBytes(String hexStr) {
  91. final bytes = hex.decode(stripHexPrefix(hexStr));
  92. if (bytes is Uint8List) return bytes;
  93. return Uint8List.fromList(bytes);
  94. }
  95. String bytesToHex(List<int> bytes,
  96. {bool include0x = false,
  97. int? forcePadLength,
  98. bool padToEvenLength = false}) {
  99. var encoded = hex.encode(bytes);
  100. if (forcePadLength != null) {
  101. assert(forcePadLength >= encoded.length);
  102. final padding = forcePadLength - encoded.length;
  103. encoded = ('0' * padding) + encoded;
  104. }
  105. if (padToEvenLength && encoded.length % 2 != 0) encoded = '0$encoded';
  106. return (include0x ? '0x' : '') + encoded;
  107. }
  108. // ------------ by myself -----------
  109. String hex2ascii(String hexString) {
  110. try {
  111. if (isHexString(hexString)) {
  112. hexString = stripHexPrefix(hexString);
  113. List<String> splitted = [];
  114. for (int i = 0; i < hexString.length; i = i + 2) {
  115. splitted.add(hexString.substring(i, i + 2));
  116. }
  117. String ascii = List.generate(splitted.length,
  118. (i) => String.fromCharCode(int.parse(splitted[i], radix: 16))).join();
  119. return ascii;
  120. } else {
  121. return '';
  122. }
  123. } catch (error) {
  124. return '';
  125. }
  126. }
  127. String ascii2hex(String asciiString) {
  128. try {
  129. if (asciiString.isNotEmpty) {
  130. String hexStr = '';
  131. for (int i = 0; i < asciiString.length; ++i) {
  132. hexStr = hexStr + asciiString.codeUnitAt(i).toRadixString(16);
  133. }
  134. return hexStr;
  135. } else {
  136. return '';
  137. }
  138. } catch (error) {
  139. return '';
  140. }
  141. }
  142. String hex2dec(String hexString) {
  143. try {
  144. if (isHexString(hexString)) {
  145. BigInt? bgInt = BigInt.tryParse(stripHexPrefix(hexString), radix:16);
  146. if (bgInt != null) {
  147. return bgInt.toRadixString(10);
  148. }
  149. }
  150. // else
  151. return '';
  152. } catch (error) {
  153. return '';
  154. }
  155. }
  156. String dec2hex(String decString) {
  157. try {
  158. if (decString.isNotEmpty) {
  159. BigInt? bgInt = BigInt.tryParse(decString, radix:10);
  160. if (bgInt != null) {
  161. return addHexPrefix(bgInt.toRadixString(16));
  162. }
  163. }
  164. // else
  165. return '';
  166. } catch (error) {
  167. return '';
  168. }
  169. }