【问题标题】:Equivalent function to struct.pack('<I', int) in dartdart 中 struct.pack('<I', int) 的等效函数
【发布时间】:2021-10-30 16:57:57
【问题描述】:

在 Python 和 JavaScript 中都有一个名为 pack 的函数

在 JavaScript 中:

struct.pack('<I', 5311)

在 Python 中

pack("<I", 5311)

将产生[0, 0, 20, 191]b'\x00\x00\x14\xbf'

dart 中是否有等价的功能?

【问题讨论】:

  • 对于不熟悉 JavaScript 中的 struct.pack 或 Python 中的 pack 的人,如果您描述了您想要的内容,将会有所帮助。您的示例也令人困惑,因为十六进制的 14bf 分别不是 242 和 115。
  • 如果你只想写一个 32 位无符号整数作为 little-endian 字节序列,你可以使用ByteData.setUint32。相关课程见dart:typed_data
  • 感谢您的注意,值 242 是错误的。我自己不熟悉struct.pack 并试图将 Python 代码转换为 dart。你能举例说明如何正确使用 ByteData.setUint32 吗?我似乎无法理解如何这样做ByteData(0000).setFloat32(4, 5311)
  • 非常感谢@jamesdlin 为我指明了正确的方向。
  • @GuyLuz 你能解释一下你的最终解决方案吗?我正在尝试在 dart 中转换 python struct.pack("&gt;ii", 1, 1)

标签: flutter dart struct


【解决方案1】:
int timestamp = 5311;
var sendValueBytes = ByteData(8);

try {
  sendValueBytes.setUint64(0, timestamp.toInt(), Endian.little);
} on UnsupportedError {
  sendValueBytes.setUint32(0, timestamp.toInt(), Endian.little);
}

Uint8List timeInBytes = sendValueBytes.buffer.asUint8List();
timeInBytes = timeInBytes.sublist(0, timeInBytes.length - 4);

String inHex = '';
timeInBytes.forEach((element) {
  inHex += element.toRadixString(16).padLeft(2, '0') + ' ';
});

print(inHex); // Will be: bf 14 00 00
print(timeInBytes); // Will be: [191, 20, 0, 0]

值得一提的是,dart 中的 int 是 8 个字节,因此要获得 4 个字节,我们需要像使用 .sublist 一样手动删除它。

在堆栈溢出中归功于this question

【讨论】:

    猜你喜欢
    • 2020-05-09
    • 2015-03-29
    • 2014-07-05
    • 2019-07-31
    • 2015-01-04
    • 2013-10-20
    • 2018-03-13
    • 2014-01-07
    相关资源
    最近更新 更多