'Convert an arbitrarily long hexadecimal string to a number in Dart?

I need to convert a string of 8-character hexadecimal substrings into a list of integers.

For example, I might have the string

001479B70054DB6E001475B3

which consists of the following substrings

001479B7    // 1341879 decimal
0054DB6E    // 5561198 decimal
001475B3    // 1340851 decimal

I'm currently using convert.hex to first convert the strings into a list of 4 integers (because convert.hex only handles parsing 2-character hex strings) and then adding/multiplying those up:

String tmp;
for(int i=0; i<=myHexString.length-8; i+=8){
  tmp = myHexString.substring(i, i+8);
  List<int> ints = hex.decode(tmp);
  int dec = ints[3]+(ints[2]*256+(ints[1]*65536)+(ints[0]*16777216));
}

Is there a more efficient way to do this?



Solution 1:[1]

You can use int.parse('001479B7', radix: 16);

https://api.dartlang.org/stable/2.4.1/dart-core/int/parse.html

so your code will look like this :

void main() {
  final fullString = '001479B70054DB6E001475B3';

  for (int i = 0; i <= fullString.length - 8; i += 8) {
    final hex = fullString.substring(i, i + 8);

    final number = int.parse(hex, radix: 16);
    print(number);
  }
}

Solution 2:[2]

Dart int parse() method also supports convert string into a number with radix in the range 2..36:

For example, we convert a Hex string into int:

var n_16 = int.parse('FF', radix: 16);
// Output 255

Solution 3:[3]

Since my Hex string came smaller than 8 elements of Byte, I did this.

String dumpHexToString(List<int> data) {
      StringBuffer sb = StringBuffer();
      data.forEach((f) {
        sb.write(f.toRadixString(16).padLeft(2, '0'));
        sb.write(" ");
      });
      return sb.toString();
    }

    String conertHexDecimal(String str1) {
      final fullString = str1;
      int number = 0;
      for (int i = 0; i <= fullString.length - 8; i += 8) {
        final hex = fullString.substring(i, i + 8);

        number = int.parse(hex, radix: 16);
        print(number);
      }
      return number.toString();
    }

void executarConersao(Uint8List data){
String conersorHexDeVar = dumpHexToString(data);
        conersorHexDeVar = conersorHexDeVar
            .substring(3, conersorHexDeVar.length)
            .replaceAll(' ', '')
            .padLeft(8, '0');
        conersorHexDeVar = conertHexDecimal(conersorHexDeVar);

        print('data $conersorHexDeVar');

}

Solution 4:[4]

For anyone who wants to convert hexadecimal numbers to 2's component, Dart / Flutter has a builtin method - .toSigned(int):

var testConversion = 0xC1.toSigned(8);
print("This is the result: " + testConversion.toString()); // prints -63

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kleak
Solution 2 Paresh Mangukiya
Solution 3 ChrisMM
Solution 4 Elmar