Last active
September 11, 2021 07:16
-
-
Save BbsonLin/064cca36fb1142ae0edc3ded03b30af9 to your computer and use it in GitHub Desktop.
Dart handle characters/strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://dartpad.dartlang.org/064cca36fb1142ae0edc3ded03b30af9