Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting integers to hex string in JavaScript

Tags:

javascript

hex

How do I convert integer byte values of red, green and blue to a hex string, which can then be assigned to a context for rendering onto a HTML5 canvas?

For example, convert cyan,

var r = 0; var g = 255; var b = 255; 

To a hex string for assigning to a context fill colour.

this.context.fillStyle = '#00FFFF'; 

Or is there a better way to do this altogether?

like image 541
Toby Wilson Avatar asked Jan 20 '11 09:01

Toby Wilson


People also ask

How do you convert a number to a string in JavaScript?

The toString() method in Javascript is used with a number and converts the number to a string. It is used to return a string representing the specified Number object. The toString() method is used with a number num as shown in the above syntax using the '. ' operator.

How do you convert a number to hexadecimal?

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.

How do you write hex in JavaScript?

JavaScript supports the use of hexadecimal notation in place of any integer, but not decimals. As an example, the number 2514 in hex is 0x9D2, but there is no language-supported way of representing 25.14 as a hex number.

What is Hexstring?

Hex string is the binary value of the string in hexadecimal notation. Since the binary value differs depending on the character encoding, the conversion result to a hex string also differs.


1 Answers

To convert a number to hex, you can use the built-in toString(16) function. Simple code:

function convert(integer) {     var str = Number(integer).toString(16);     return str.length == 1 ? "0" + str : str; };  function to_rgb(r, g, b) { return "#" + convert(r) + convert(g) + convert(b); }  var color = to_rgb(r, g, b); 
like image 127
nemisj Avatar answered Sep 28 '22 03:09

nemisj