user7809745
user7809745

Reputation:

Convert int32 to bytes List in dart

I want to convert int32 into bytes array.

specifically i want to convert 477 to bytes array like [el1,el2,el3,el4] i tried utf8.encode(477.toString()); and got [52, 55, 55]

Upvotes: 8

Views: 13059

Answers (1)

lrn
lrn

Reputation: 71893

The easiest approach would be to create a byte list (Uint8list), then view the underlying buffer as a 32-bit integer list (Int32List) and store the integer there. That will allow you to read back the bytes.

import "dart:typed_data";

Uint8List int32bytes(int value) =>
    Uint8List(4)..buffer.asInt32List()[0] = value;

This will store the integer using the platform's byte ordering. If you want a particular byte ordering, you can use a ByteData view instead, which allows writing bytes in any endianness and position:

Uint8List int32BigEndianBytes(int value) =>
    Uint8List(4)..buffer.asByteData().setInt32(0, value, Endian.big);

Upvotes: 26

Related Questions