【问题标题】:Unreadable Int16 from UInt8List, wrong data when cast asByteArrayUInt8List 中的 Int16 不可读,转换为字节数组时数据错误
【发布时间】:2018-12-22 16:46:15
【问题描述】:

我试图从数据中获取 int,short,从 websocket 获取数据,但是有些事情是错误的,当我从 UInt8List -> Byte Data -> UInt8List 转换时,它在我的数组中添加了 2 个新的 uint8。任何人都建议我如何从字节数组中获取 int 的正确方法。 (这是大端,我在 Swift 中的代码和在 Dart 中的基本写入数据仍然正确)。感谢大家阅读本文。

我正在使用 'dart:typed_data';并从 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 ) 

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    还有其他事情发生,因为您的代码没有添加任何额外的字节 - 实际上,它没有使用 array

    这段代码:

    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 )
    }
    

    打印(如预期)

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

    编辑 - 正如评论中所建议的那样,您拥有的 Uint8List 实际上是一个具有非零偏移量的 ByteBuffer 视图。因此,responseData.buffer 是底层缓冲区,其中包括额外的字节。最简单的解决方案是制作视图的副本。

    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
    }
    

    【讨论】:

    • 当我尝试转换为另一种类型时,它会抛出异常,所以我认为它的 UInt8List: Unhandled exception: type '_Uint8ArrayView' is not a subtype of type 是的,我真的不明白为什么 responseData 可以改变,打印(响应数据); // [0, 1, 0, 1, 0, 1, 49] var shortValue = responseData.asByteData().getInt16(0);打印(短值); // -32249 Uint8List responseTest = Uint8List.fromList([0, 1, 0, 1, 0, 1, 49]);打印(响应测试); // [0, 1, 0, 1, 0, 1, 49] var shortTest = responseTest.buffer.asByteData().getInt16(0);打印(短测试); //当然是1
    • 我怀疑您得到的视图没有偏移量为零,例如来自Uint8List.view()。您最简单的解决方法是在执行任何其他操作之前先创建一个干净的Uint8ListUint8List copy = Uint8List.fromList(responseData); 然后使用copy.buffer.asByteData()
    猜你喜欢
    • 2016-11-14
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多