Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: convert decimal to hex

Tags:

dart

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?

like image 313
Nazaal Avatar asked Sep 16 '18 16:09

Nazaal


People also ask

How do you convert decimal to hex?

Take decimal number as dividend. Divide this number by 16 (16 is base of hexadecimal so divisor here). Store the remainder in an array (it will be: 0 to 15 because of divisor 16, replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Repeat the above two steps until the number is greater than zero.


Video Answer


2 Answers

 int.toRadixString(16) 

does that.

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

like image 90
Günter Zöchbauer Avatar answered Oct 16 '22 11:10

Günter Zöchbauer


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
like image 37
Suragch Avatar answered Oct 16 '22 09:10

Suragch