2

I have a set of numbers like 4294933099, 4283744614, 4293898800 that I want to use in a web page as RGB or HEX colors.

I never saw this type of color format before but googling lead me to this page that identifies those numbers as Android android.graphics.Color, what I want is having my own JavaScript function that converts those humbers to safe Hex or RGB colors to use in a web page.

enter image description here

tinyCoder
  • 350
  • 13
  • 37
  • 1
    I think this should work https://stackoverflow.com/questions/11866781/how-do-i-convert-an-integer-to-a-javascript-color, check the 4th answer with 21 votes, let me know if it worked for you will add it as a reference in the answer so it will be helpful for future reference – Learner May 16 '20 at 20:23

2 Answers2

3

Actually android color are just decimal numbers, so if you convert them to hexadecimal strings you reach the hex color but as ARGB.

hexARGBColor = color.toString(16);
acbay
  • 832
  • 7
  • 7
2

android.graphics.Colors are in hexadecimal AARRGGBB (Alpha-Red-Green-Blue) format, converted to decimals.

For example, 4294933099 is FFFF7A6B in hexadecimal, so it becomes rgba(255, 122, 107, 1) or #FF7A6BFF.

If you want to use the rgba() syntax, you can use this division approach, that avoids converting numbers to hex:

function androidToRgba(color){
  const colorArray = []
  for(let i=0; i<4; i++){
    colorArray.push(color % 256)
    color>>>=8
  }
  const alpha = colorArray.pop() / 255
  return `rgba(${colorArray.reverse()},${alpha})`
}

console.log(androidToRgba(4294933099))
console.log(androidToRgba(4283744614))
console.log(androidToRgba(4293898800))

Alternatively, if you want to use the new #RRGGBBAA color syntax, or ignore the alpha and use standard HEX (#RRGGBB), you can use this instead:

function androidToHex(color){
  const [, alpha, ...colorArray] = ('00000000' + color.toString(16)).slice(-8).match(/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i)
  return `#${colorArray.join('')}${alpha}`
}

console.log(androidToHex(4294933099))
console.log(androidToHex(4283744614))
console.log(androidToHex(4293898800))

Although both of the above solutions work, I highly recommend the former, as the rgba() syntax has better support than #RRGGBBAA, and the first function is also around 9 times faster.

FZs
  • 16,581
  • 13
  • 41
  • 50