Dart:将十进制转换为十六进制

N92*_*991 3 dart

我一直在寻找一种将Dart编程语言中的十进制数字转换为十六进制格式的函数/方法。

例如,HexCodec类中的hex.encode方法无法转换十进制1111(十六进制值为457),而是给出异常“ FormatException:无效字节0x457。(偏移量为0)”。

如果有人可以帮助我,那将很棒

谢谢

Sur*_*gch 23

这是一个更完整的例子:

final myInteger = 2020;
final hexString = myInteger.toRadixString(16);      // 7e4
Run Code Online (Sandbox Code Playgroud)

基数仅表示基数,因此16表示基数 16。您可以使用相同的方法来创建二进制字符串:

final binaryString = myInteger.toRadixString(2);    // 11111100100
Run Code Online (Sandbox Code Playgroud)

如果您希望十六进制字符串始终为四个字符长,则可以用零填充左侧:

final paddedString = hexString.padLeft(4, '0');     // 07e4
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢大写十六进制:

final uppercaseString = paddedString.toUpperCase(); // 07E4
Run Code Online (Sandbox Code Playgroud)

这里还有一些其他有趣的事情:

print(0x7e4); // 2020

int myInt = int.parse('07e4', radix: 16);
print(myInt); // 2020
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 8

 int.toRadixString(16) 
Run Code Online (Sandbox Code Playgroud)

做到这一点。

另请参阅https://groups.google.com/a/dartlang.org/forum/m/#!topic/misc/ljkYEzveYWk

  • 如果要使用固定宽度的十六进制字符串,也可以使用`int.toRadixString(16).padLeft(4,'0')`来确保(至少)四位数。 (7认同)