I have written a hex to 8 bit online tool at https://aiseka.com/tool/convert-color-hex-code-to-8-bit
Here is the core code for the tool, code is very easy.
"use client";
import React, { useState } from "react";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
const hexTo8Bit = (hex: string) => {
const bigint = parseInt(hex.slice(1), 16);
const r = (bigint >> 16) & 255;
const g = (bigint >> 8) & 255;
const b = bigint & 255;
return `${r},${g},${b}`;
};
const bit8ToHex = (bit8: string) => {
const [r = 0, g = 0, b = 0] = bit8.split(",").map(Number);
return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase()}`;
};
export const Tool = () => {
const [hex, setHex] = useState("");
const [bit8, setBit8] = useState("");
const handleHexChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setHex(e.target.value);
};
const handleBit8Change = (e: React.ChangeEvent<HTMLInputElement>) => {
setBit8(e.target.value);
};
const handleHexBlur = () => {
setBit8(hexTo8Bit(hex));
};
const handleBit8Blur = () => {
setHex(bit8ToHex(bit8));
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
if (e.currentTarget.name === "hex") {
setBit8(hexTo8Bit(hex));
} else if (e.currentTarget.name === "bit8") {
setHex(bit8ToHex(bit8));
}
}
};
const handleConvert = () => {
setBit8(hexTo8Bit(hex));
setHex(bit8ToHex(bit8));
};
return (
<div className="grid w-full gap-8 rounded-md bg-muted p-4">
<div className="grid grid-cols-2 gap-4">
<div className="grid gap-2">
HEX code:
<Input
name="hex"
value={hex}
onChange={handleHexChange}
onBlur={handleHexBlur}
onKeyDown={handleKeyDown}
/>
</div>
<div className="grid gap-2">
8 Bit:
<Input
name="bit8"
value={bit8}
onChange={handleBit8Change}
onBlur={handleBit8Blur}
onKeyDown={handleKeyDown}
/>
</div>
</div>
<Button className="mx-auto w-1/2" onClick={handleConvert}>
Convert
</Button>
</div>
);
};