首页 > 解决方案 > 如何在 Dart 中将 Uint8List 转换为十进制数?

问题描述

我有一个 Uint8List 数据列表,例如:

Uint8List uintList = Uint8List.fromList([10, 1]);

如何将这些数字转换为十进制数?

int decimalValue = ???  // in this case 265

标签: dartbyte

解决方案


根据我对您的问题的理解,您希望 decimalValue 是一个整数,其中最低有效字节为(十进制)10,之后的字节为 1。这将导致值 1 * 256 + 10 = 266。如果你的意思是相反的字节,它将是 10 * 256 + 1 = 2560 + 1 = 2561。

我实际上对飞镖没有任何经验,但我认为与此类似的代码会起作用:

int decimalValue = 0;
for (int i = 0; i < uintList.length; i++) {
    decimalValue = decimalValue << 8; // shift everything one byte to the left
    decimalValue = decimalValue | uintList[i]; // bitwise or operation
}

如果它没有产生您想要的数字,您可能不得不向后迭代循环,这需要更改一行代码:

for (int i = uintList.length-1; i >= 0; i--) {

推荐阅读