Dart: how to convert Hex String to Ascii string

39 Views Asked by At

need some help to convert Hex String to Ascii string.

I am using sample functions from here

Sample Hex = 20354653474955 I am getting this error:

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: RangeError (end): Invalid value: Not in inclusive range 20..21: 22

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FormatException: Invalid radix-16 number (at character 1)

Any suggestion to get this work on Dart?

Here is the function I am using:

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

There are 2 best solutions below

2
Kay On

I figured it out. The substring argument (i *2,(i *2) +2) seems incorrect. It was skipping some sequences of the Hex string.

0
julemand101 On

Can't reproduce your issue and it seems like you have already fixed in yourself but without telling what the exact solution ended up being.

Since I did end up playing around with alternative ways of converting hex string into ASCII string, I will post my attempt here, which I think looks a bit cleaner:

String hexToAscii(String hexString) => hexString.splitMapJoin(RegExp(r'.{2}'),
    onMatch: (m) => String.fromCharCode(int.parse(m[0]!, radix: 16)));
void main() {
  String hex = '20354653474955';
  print(hexToAscii(hex)); //  5FSGIU
}

I am sure there are edge cases that should be handled but I don't think this solution are worse in handling those edge cases compared to the original function.