Home > Blockchain >  Convert ASCII to hex
Convert ASCII to hex

Time:05-18

I want convert ASCII values to hex. In Java, I often use the function:

private static String asciiToHex(String asciiStr) {
    char[] chars = asciiStr.toCharArray();
    StringBuilder hex = new StringBuilder();
    for (char ch : chars) {
        hex.append(Integer.toHexString((int) ch));
    }

    return hex.toString();
}

Is there any method in Dart to convert to hex value like Integer.toHexString in Java?

Example:

youtube.com

Output

796F75747562652E636F6D

CodePudding user response:

The equivalent of Integer.toHexString would be to call .toRadixString(16) on an integer value.

The asciiToHex function can be translated to dart like so:

String asciiToHex(String asciiStr) {
  List<int> chars = asciiStr.codeUnits;
  StringBuffer hex = StringBuffer();
  for (int ch in chars) {
    hex.write(ch.toRadixString(16).padLeft(2, '0'));
  }
  return hex.toString();
}

CodePudding user response:

Try

String hexToAscii(String hexString) => List.generate(
      hexString.length ~/ 2,
      (i) => String.fromCharCode(
          int.parse(hexString.substring(i * 2, (i * 2)   2), radix: 16)),
    ).join();
  • Related