Nazaal
Nazaal

Reputation: 447

Dart: convert decimal to hex

I've been searching for a way to convert decimal numbers to hexadecimal format in the Dart programming language.

The hex.encode method in the HexCodec class, for example, cannot convert the decimal 1111 (which has a hex value of 457) and instead gives an exception:

FormatException: Invalid byte 0x457. (at offset 0)

How do I convert a decimal number to hex?

Upvotes: 34

Views: 42338

Answers (2)

Suragch
Suragch

Reputation: 512666

Here is a little fuller example:

final myInteger = 2020;
final hexString = myInteger.toRadixString(16);      // 7e4

The radix just means the base, so 16 means base-16. You can use the same method to make a binary string:

final binaryString = myInteger.toRadixString(2);    // 11111100100

If you want the hex string to always be four characters long then you can pad the left side with zeros:

final paddedString = hexString.padLeft(4, '0');     // 07e4

And if you prefer it in uppercase hex:

final uppercaseString = paddedString.toUpperCase(); // 07E4

Here are a couple other interesting things:

print(0x7e4); // 2020

int myInt = int.parse('07e4', radix: 16);
print(myInt); // 2020

Upvotes: 24

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658067

 int.toRadixString(16) 

does that.

See also https://groups.google.com/a/dartlang.org/forum/m/#!topic/misc/ljkYEzveYWk

Upvotes: 77

Related Questions