How to achieve buffer of nodejs similar functionality in dart
359
This is because bytes are in reversed order in comparison to Buffer. So rewriting this to:
List<int> _createUInt32LE(int value, {int size: 4}) {
final re = Uint8List(size)..buffer.asByteData().setUint32(0, value);
return re.reversed.toList();
}
should work
EDIT: Solution above is not most performant. This should be better one:
List<int> _createUInt32LE(int value, {int size: 4}) {
final result = Uint8List(size);
for(int i = 0; i < size; i++, value >>= 8) {
result[i] = value & 0xFF;
}
return result;
}
Author by
Kawaljeet Singh
Updated on December 23, 2022Comments
-
Kawaljeet Singh over 1 year
I am stuck in writing a similar code of nodejs in dart.
_createUInt32LEBuffer(value, bufferSize = 4) { const buffer = Buffer.alloc(bufferSize); buffer.writeUInt32LE(value, 0); if (i === 300) { console.log(Buffer.from(buffer).toString('base64').toString()); } return buffer; }
I have searched the web and got this solution but it's not working correctly:
Uint8List int32bytes(int value, {int size: 4}) { final re = Uint8List(size)..buffer.asUint8List(); re[0] = value; if (value == 300) { print(base64Encode(re)); } return re;
}
-
julemand101 over 3 yearsCan you give an example of input and expected output values for us without any experience with nodejs? :)
-
Kawaljeet Singh over 3 yearswhen the value is given as 300 then the output in base64 in nodejs is LAEAAA== but with dart the output after base64 is LAAAAA== and so on as it reches to higher values the output difference increases. for lower values like 0 to 200 the output is same
-