DEV Community

Discussion on: Daily Challenge #236 - RGB to Hex Conversion

Collapse
 
pavi2410 profile image
Pavitra Golchha • Edited

BeanShell

int clip(int n) {
    return Math.max(0, Math.min(n, 255));
}

String rgb(int r, int g, int b) {
    r = clip(r);
    g = clip(g);
    b = clip(b);
    return String.format("%02x%02x%02x", new Object[] { r, g, b}).toUpperCase();
}

show();
rgb(255, 255, 255); // returns FFFFFF
rgb(255, 255, 300); // returns FFFFFF
rgb(0,0,0); // returns 000000
rgb(148, 0, 211); // returns 9400D3
rgb(-20,275,125); // returns 00FF7D

Run this code using AJShA Android app