Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

hex

flutter

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?

like image 812
Magnus Avatar asked Aug 27 '19 13:08

Magnus


People also ask

How do you get hex code from color flutter?

Steps to use Hexadecimal (Hex) Color Code Strings in FlutterStep 1: Remove the # sign. Step 2: Add 0xFF at the beginning of the color code. Step 3: Place it inside the Color class like this Color(0xFFbfeb91).


1 Answers

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);
  }
}
like image 99
Kleak Avatar answered Nov 04 '22 14:11

Kleak