0
votes

I tried to get int, short from data, the data get from websocket, but some thing is wrong, and when i cast from UInt8List -> Byte Data -> UInt8List, it add 2 new uint8 in my array. Any one suggest me how is correct way to get int from byte array. (It's big Endian, my code in Swift and the base write data in Dart still correct). Thank anyone for reading this.

I am using 'dart:typed_data'; and get data from WebSocket (dart:io)

print(responseData); // UInt8List: [0, 1, 0, 1, 0, 1, 49]
var byteData = responseData.buffer.asByteData();
var array = byteData.buffer.asUint8List(); 
print(array); // UInt8List: [130, 7, 0, 1, 0, 1, 0, 1, 49]
var shortValue = responseData.buffer.asByteData().getInt16(0);
print(shortValue); // -32249 ( 2 first byte: [0 ,1] so it must be 1 ) 
1

1 Answers

3
votes

There's something else going on, because your code does not add any extra bytes - and actually, it doesn't use array.

This code:

import 'dart:typed_data';

void main() {
  Uint8List responseData = Uint8List.fromList([0, 1, 0, 1, 0, 1, 49]);
  print(responseData); // UInt8List: [0, 1, 0, 1, 0, 1, 49]
  var byteData = responseData.buffer.asByteData();
  //var array = byteData.buffer.asUint8List();
  //print(array); // UInt8List: [130, 7, 0, 1, 0, 1, 0, 1, 49]
  var shortValue = responseData.buffer.asByteData().getInt16(0);
  print(shortValue); // -32249 ( 2 first byte: [0 ,1] so it must be 1 )
}

prints (as expected)

[0, 1, 0, 1, 0, 1, 49]
1

EDIT - as suggested in the comment, the Uint8List you have is in fact a view on a ByteBuffer with a non-zero offset. So, responseData.buffer is that underlying buffer, which includes additional bytes. The simplest solution is to make a copy of the view.

import 'dart:typed_data';

void main() {
  Uint8List original = Uint8List.fromList([130, 7, 0, 1, 0, 1, 0, 1, 49]);
  print(original);

  Uint8List view = Uint8List.view(original.buffer, 2);
  print(view);
  print(view.buffer.lengthInBytes); // prints 9
  print(view.buffer.asByteData().getUint16(0)); // unexpected result

  Uint8List copy = Uint8List.fromList(view);
  print(copy.buffer.lengthInBytes); // prints 7
  print(copy.buffer.asByteData().getUint16(0)); // expected result
}