将int32转换为dart中的字节列表 [英] Convert int32 to bytes List in dart

查看:471
本文介绍了将int32转换为dart中的字节列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将int32转换为字节数组.

I want to convert int32 into bytes array.

具体来说,我想将477转换为字节数组,例如[el1,el2,el3,el4] 我尝试了utf8.encode(477.toString()); 并得到[52,55,55]

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]

推荐答案

最简单的方法是创建一个字节列表(Uint8list),然后将基础缓冲区视为32位整数列表(Int32List)并将整数存储在那里.这样您就可以读回字节.

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;;

这将使用平台的字节顺序存储整数.如果要特定的字节顺序,则可以使用ByteData视图,该视图允许以任何字节序和位置写入字节:

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

这篇关于将int32转换为dart中的字节列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆