Home > database >  Dart: Parsing byte data to a string
Dart: Parsing byte data to a string

Time:03-10

I have following code. What I am trying to do is parse BLE service data to get EddyStone Namespace and InstanceID. is parse byte data into a string.

import 'dart:typed_data';
import 'dart:convert';

main(){
    var list = [0, 2, 46, 80, 128, 106, 163, 130, 85, 170, 217, 250, 42, 21, 78, 45, 0, 85, 0, 0];
    Uint8List serviceData = Uint8List.fromList(list);
    ByteData data = ByteData.sublistView(serviceData, 0, 10); //for namespace 10 byte  
    var abc = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);

    var dta = utf8.decode(abc);
    print(dta);
}

i got following error on utf8.decode(abc);

Unhandled Exception: FormatException: Unexpected extension byte (at offset 4)

Can anybody tell me where I am wrong? I am new to dart.

Thanks

CodePudding user response:

From the comments, it seems that you're asking for a hexadecimal representations for sequences of bytes.

Note that strings you expected in your comments for the "namespace" and "instance" IDs seem wrong. It looks like you just converted the first 16 bytes of your List, but since your original List is 20 bytes, it seems like it's supposed to be the entire 20-byte Service Data Block.

From the specification you linked to in your comments, the "namespace" ID starts at offset 2 and is 10 bytes long. The "instance" ID starts at offset 12 and is 6 bytes long. Therefore, you must first extract those subsequences. Once you have the desired sublist, you can use int.toRadixString to convert each byte to a hexadecimal string, use String.padLeft to force using two hexadecimal digits, and then use List.join to combine them all into a single String:

String getHexString(
  List<int> list, {
  required int offset,
  required int length,
}) {
  var sublist = list.getRange(offset, offset   length);
  return [
    for (var byte in sublist)
      byte.toRadixString(16).padLeft(2, '0').toUpperCase()
  ].join();
}

void main() {
  var list = [0, 2, 46, 80, 128, 106, 163, 130, 85, 170, 217, 250, 42, 21, 78, 45, 0, 85, 0, 0];

  var namespaceId = getHexString(list, offset: 2, length: 10);
  var instanceId = getHexString(list, offset: 12, length: 6);

  print(namespaceId); // Prints: 2E50806AA38255AAD9FA
  print(instanceId); // Prints: 2A154E2D0055
}
  • Related