2

Im SOO very new to Flutter and I dont know where to begin. I need to convert a string like this 349caa523e0787003e0787033e053e08 to (what I assume is an array in flutter) to write to flutter_blue.

I need to convert it to 0x39, 0x9c,0xaa .... so that I can pass this to await d.write([0xXX, 0xXX])

I did get some help doing it Javascript eg.

var s = "ab05d705";
var result = [];

for (var i = 0; i < s.length; i += 2) {
 result.push(parseInt(s.substring(i, i + 2), 16));
}

result = Uint8Array.from(result);

Any help would be appreciate. Thanks

Robbal
  • 101
  • 1
  • 2
  • 8
  • try this: `var list = RegExp('..') .allMatches("ab05d705") .map((m) => int.parse(m.group(0), radix: 16)); print(list);` – pskink Feb 15 '21 at 10:51

2 Answers2

1

You can perform any of the option from below to covert it:

Option 1:

String s = new String.fromCharCodes(inputAsUint8List);
var outputAsUint8List = new Uint8List.fromList(s.codeUnits);

Option 2:

List<int> list = 'xxx'.codeUnits;
Uint8List bytes = Uint8List.fromList(list);
String string = String.fromCharCodes(bytes);
ZealousWeb
  • 1,647
  • 1
  • 10
  • 11
0

If you want something similar to your Javascript snippet:

var s = "ab05d705";
var result = [];

for (var i = 0; i < s.length; i += 2) {
  result.add(int.parse(s.substring(i, i + 2), radix: 16));
}
Michael Kotzjan
  • 2,093
  • 2
  • 14
  • 23
  • Thank you . This is closer. I think I now need to work out how to get it into Uint8Array as I now get this error when sent to flutter_blue ''' Unhandled Exception: type 'List' is not a subtype of type 'List'' – Robbal Feb 16 '21 at 06:05
  • 1
    you could try https://api.flutter.dev/flutter/dart-typed_data/Uint8List/Uint8List.fromList.html but I'm not sure what data type d.write expects – Michael Kotzjan Feb 16 '21 at 06:11
  • 1
    Thanks this seems to work await _ledChar.write(result.cast()); but I still need to see if its sending the correct data – Robbal Feb 16 '21 at 06:24
  • 1
    Thank you all for the help . Its working . I am now starting to understand Flutter – Robbal Feb 16 '21 at 07:30
  • @MichaelKotzjan can you also please help me with this https://stackoverflow.com/q/74522437/8036360 – Siddy Hacks Nov 21 '22 at 17:55