From ef8c233e6c0aa0b9f481fef17c0b9561a83c6b33 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Mon, 12 Sep 2022 15:07:10 +0300 Subject: [PATCH] Add decimal to hex --- blog_posts/js-decimal-to-hex.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 blog_posts/js-decimal-to-hex.md diff --git a/blog_posts/js-decimal-to-hex.md b/blog_posts/js-decimal-to-hex.md new file mode 100644 index 000000000..2ff065d44 --- /dev/null +++ b/blog_posts/js-decimal-to-hex.md @@ -0,0 +1,29 @@ +--- +title: "Tip: Convert decimal number to hexadecimal" +shortTitle: Decimal to hexadecimal +type: tip +tags: javascript,math +expertise: beginner +author: chalarangelo +cover: blog_images/waves-from-above.jpg +excerpt: Ever needed to convert a decimal number to hexadecimal? Here's a quick and easy way to do it. +firstSeen: 2022-09-21T05:00:00-04:00 +--- + +Numeric values are represented in decimal format by default, when converted to strings. If you want to display them in hexadecimal format, you can use `Number.prototype.toString()` and pass the base you want to use (`16`) as an argument. + +```js +const decimalToHex = dec => dec.toString(16); + +decimalToHex(0); // '0' +decimalToHex(255); // 'ff' +``` + +Conversely, the opposite might also be needed. You can use `parseInt()` to convert a string to a number in a given base. If you don't specify a base, it will default to `10`. + +```js +const hexToDecimal = hex => parseInt(hex, 16); + +hexToDecimal('0'); // 0 +hexToDecimal('ff'); // 255 +```