Skip to content

Instantly share code, notes, and snippets.

@BbsonLin
Last active September 11, 2021 07:16
Show Gist options
  • Save BbsonLin/064cca36fb1142ae0edc3ded03b30af9 to your computer and use it in GitHub Desktop.
Save BbsonLin/064cca36fb1142ae0edc3ded03b30af9 to your computer and use it in GitHub Desktop.
Dart handle characters/strings
List<int> hexToUnits(String hexStr, {int combine=2}) {
hexStr = hexStr.replaceAll(" ", "");
List<int> hexUnits = [];
for(int i = 0;i < hexStr.length;i+=combine) {
hexUnits.add(hexToInt(hexStr.substring(i, i+combine)));
}
return hexUnits;
}
int hexToInt(String hex) {
return int.parse(hex, radix: 16);
}
String intToHex(int i, {int pad=2}) {
return i.toRadixString(16).padLeft(pad, '0').toUpperCase();
}
void main() {
List<List<int>> asciiList = [[52], [53, 54]];
print(asciiList.map((List<int> char) => String.fromCharCodes(char)).join()); // 456
print(160.toRadixString(16).toUpperCase()); // A0
print(int.parse("A012", radix: 16)); // 40978
print("A0 12 13".replaceAll(" ", "")); // A01213
print("ABC".codeUnits); // [65, 66, 67]
String hexStrs = "7E A1 12 00 50 00 03 7E";
print(hexToUnits(hexStrs)); // [126, 161, 18, 0, 80, 0, 3, 126]
String hexStr = "7E";
print(hexToInt(hexStr)); // 126
int hexInt = 75;
print(intToHex(hexInt)); // 4B
List<int> cmdList = [126, 161, 18, 0, 179, 126];
print(cmdList.first); // 126
print(cmdList.last); // 126
print([126, 161, 18, 0, 80, 0, 3, 126].map((int char) => intToHex(char)).toList().join()); // 7EA112005000037E
}
@BbsonLin
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment