{ }codelper
base conversionsubstringsP0416

Decoding hex color codes

Colors on web pages are written as color codes: # followed by hexadecimal characters.
The hexadecimal characters are 0 to 9, a to f and A to F; a and A are 10, b and B are 11, …, f and F are 15.
Uppercase and lowercase letters have the same value.
If six characters follow #, they are, two at a time from the front, the brightness of red, green and blue, each written as a two-digit hexadecimal number.
The value of a two-digit hexadecimal number xy is (value of x) × 16 + (value of y) (#FF8000 → 255 128 0).
If only three characters follow #, it is the short form, equal to the six-character code in which each of the three characters is written twice (#f80 → #ff8800 → 255 136 0).
For each color code, print the brightness of red, green and blue converted to decimal.

Input
The first line gives the number of color codes n.
Each of the next n lines gives one color code.
A color code consists only of one # immediately followed by 3 or 6 hexadecimal characters, with no spaces.
Uppercase and lowercase letters may be mixed within one code (#1a2B3c).
1 ≤ n ≤ 100
Output
One line per color code, in input order: the brightness of red, green and blue separated by single spaces.
Each brightness is a decimal integer from 0 to 255 with no leading zeros (#000 → 0 0 0).
Example 1 · stdin
4
#FF8000
#f80
#1a2B3c
#000
stdout
255 128 0
255 136 0
26 43 60
0 0 0
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

The tools that turn a two-digit hex number into decimal are Python int(t, 16), JS/TS parseInt(t, 16), Java Integer.parseInt(t, 16), C# Convert.ToInt32(t, 16) and C++ std::stoi(t, nullptr, 16), and all of them accept both uppercase and lowercase.
C has strtol(t, NULL, 16) too, but you would have to copy the two characters into their own '\0'-terminated string, so here a small function gives the value of one character and the result is (high digit) × 16 + (low digit).
Craykon has no tool of its own for reading hex (("0x" + "ff").ToNumber() happens to give 255 today, but that is not documented, so don't rely on it), so the position of the character is used as its value: "0123456789abcdef".IndexOf(c.ToLower()).
Trap one: thinking only of uppercase.
In C, using just c - 'A' + 10 for non-digits makes 'a' 42, so #1a2B3c comes out as 58 43 92 (line three of the example).
In Craykon, searching without lowercasing first finds no "F", IndexOf gives -1, and #FF8000 becomes -17 128 0.
Trap two: the short form.
The f of #f80 means ff (255), not f0 (240).
Just multiplying the character's value by 16 gives 240 128 0, and reading the whole thing without expanding it, as in parseInt("f80", 16), then splitting the bits gives 0xf80 = 3968, so 0 15 128 (line two of the example).
A character written twice is worth (its value) × 17.
Trap three: cutting two characters at a time from position 0 without dropping #.
JS parseInt("#F", 16) gives NaN without any error, so #FF8000 comes out as NaN 248 0, and Python int("#F", 16) stops with a ValueError.

Pythonmain.py · 7 lines
n = int(input())for _ in range(n):    digits = input().strip()[1:]  # '#'는 떼어 낸다    if len(digits) == 3:        digits = "".join(d * 2 for d in digits)  # f80 → ff8800    # 두 글자씩 16진수로 읽는다(int는 대문자·소문자를 모두 받는다)    print(*(int(digits[i:i + 2], 16) for i in range(0, 6, 2)))
JavaScriptmain.js · 13 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n"); const n = Number(lines[0]);const result = [];for (let i = 1; i <= n; i++) {  let digits = lines[i].trim().slice(1); // '#'는 떼어 낸다  if (digits.length === 3) {    digits = [...digits].map((d) => d + d).join(""); // f80 → ff8800  }  const rgb = [0, 2, 4].map((k) => parseInt(digits.slice(k, k + 2), 16));  result.push(rgb.join(" "));}console.log(result.join("\n"));
TypeScriptmain.ts · 14 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n"); const n: number = Number(lines[0]);const result: string[] = [];for (let i = 1; i <= n; i++) {  let digits: string = lines[i].trim().slice(1); // '#'는 떼어 낸다  if (digits.length === 3) {    digits = [...digits].map((d) => d + d).join(""); // f80 → ff8800  }  const rgb: number[] = [0, 2, 4].map((k) => parseInt(digits.slice(k, k + 2), 16));  result.push(rgb.join(" "));}console.log(result.join("\n"));
JavaMain.java · 25 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(br.readLine().trim());        StringBuilder out = new StringBuilder();        for (int i = 0; i < n; i++) {            String digits = br.readLine().trim().substring(1); // '#'는 떼어 낸다            if (digits.length() == 3) {                StringBuilder full = new StringBuilder();                for (char d : digits.toCharArray()) full.append(d).append(d); // f80 → ff8800                digits = full.toString();            }            for (int k = 0; k < 6; k += 2) {                if (k > 0) out.append(' ');                out.append(Integer.parseInt(digits.substring(k, k + 2), 16));            }            out.append('\n');        }        System.out.print(out);    }}
C#Main.cs · 26 lines
using System;using System.Text; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine().Trim());        var sb = new StringBuilder();        for (int i = 0; i < n; i++)        {            string digits = Console.ReadLine().Trim().Substring(1); // '#'는 떼어 낸다            if (digits.Length == 3)            {                var full = new StringBuilder();                foreach (char d in digits) full.Append(d).Append(d); // f80 → ff8800                digits = full.ToString();            }            int r = Convert.ToInt32(digits.Substring(0, 2), 16);            int g = Convert.ToInt32(digits.Substring(2, 2), 16);            int b = Convert.ToInt32(digits.Substring(4, 2), 16);            sb.Append($"{r} {g} {b}\n");        }        Console.Write(sb.ToString());    }}
C++main.cpp · 22 lines
#include <iostream>#include <string> int main() {    int n;    std::cin >> n;    std::string code;    for (int i = 0; i < n; i++) {        std::cin >> code;        std::string digits = code.substr(1);  // '#'는 떼어 낸다        if (digits.size() == 3) {            std::string full;            for (char d : digits) full += std::string(2, d);  // f80 → ff8800            digits = full;        }        for (int k = 0; k < 6; k += 2) {            if (k > 0) std::cout << ' ';            std::cout << std::stoi(digits.substr(k, 2), nullptr, 16);        }        std::cout << '\n';    }}
Cmain.c · 32 lines
#include <stdio.h>#include <string.h> /* 16진수 글자 하나의 값: 0~9, a~f, A~F */int hex_value(char c) {    if (c >= '0' && c <= '9') return c - '0';    if (c >= 'a' && c <= 'f') return c - 'a' + 10;    return c - 'A' + 10;} int main(void) {    int n;    char code[16];    scanf("%d", &n);    for (int i = 0; i < n; i++) {        scanf("%15s", code);        const char *digits = code + 1; /* '#'는 건너뛴다 */        int shortForm = strlen(digits) == 3;        for (int k = 0; k < 3; k++) {            int hi, lo;            if (shortForm) {                hi = lo = hex_value(digits[k]); /* f → ff */            } else {                hi = hex_value(digits[2 * k]);                lo = hex_value(digits[2 * k + 1]);            }            printf(k == 0 ? "%d" : " %d", hi * 16 + lo);        }        putchar('\n');    }    return 0;}
Craykonmain.cray · 26 lines
// 16진수 글자 하나의 값: 소문자로 바꾼 뒤 자리를 찾는다("F" → "f" → 15)자릿값(c){    return "0123456789abcdef".IndexOf(c.ToLower());} n = Console.ReadLine().ToNumber();for (i = 0; i < n; i++){    숫자들 = Console.ReadLine().Trim().Substring(1); // '#'는 떼어 낸다    if (숫자들.Length == 3)    {        늘린것 = "";        foreach (d in 숫자들)        {            늘린것 = 늘린것 + d + d; // f80 → ff8800        }        숫자들 = 늘린것;    }    밝기 = [];    for (k = 0; k < 6; k += 2)    {        밝기.Add(자릿값(숫자들.Substring(k, 1)) * 16 + 자릿값(숫자들.Substring(k + 1, 1)));    }    Console.WriteLine(밝기);}