Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

54
Views
Reactjs - percentage to 8-bit hex string

I am not quite sure how to solve this problem, Question:

**Converts a percentage to 8bit hex string linearly

  • Valid percentage values are 0 to 100 included
  • If percentage is out of this range, cap the value to min/max
  • Returned string needs to be 2 char long hex value
  • Use rounding for decimal values
  • Examples: 0 --> '00', 1 --> '03', 100 --> 'ff' @param {number} percentage - percentage value @returns {string} 8bit hex string between '00' and 'ff'**
const percentageTo8BitHex = (percentage) => {
    // Insert your code here
};

// This functions is here to test the result only
export const testConversion = () => {
    const fixedValuesToTest = [-1, 0, 1, 100, 101];
    const fixedExpectedResults = ['00', '00', '03', 'FF', 'FF'];
    const randomValuesToTest = [];
    for (let i = 0; i < 5; i++) {
        randomValuesToTest.push(Math.random() * 98 + 1);
    }
    fixedValuesToTest.forEach((value, index) => {
        console.log(
            `Testing: ${value} - expected ${fixedExpectedResults[index]} - received ${percentageTo8BitHex(value)}`,
        );
    });
    randomValuesToTest.forEach((value) => {
        const hexString = percentageTo8BitHex(value);
        const valueFromHex = parseInt(hexString, 0b10000) / 0b11111111;
        const valid = Math.abs(valueFromHex * 0x64 - value) < 0b10;
        console.log(`Testing: ${value} - received ${hexString} (${valueFromHex}) - ${valid ? 'VALID' : 'INVALID'}`);
    });
};

My result is:

Firstr i have to round Percentage = Math.max(0, Math.min(100, percentage))

Full scale conversion 0..100 => 0..FF equals 0..255

So I have to convert it like this? hex = 255 * (percentage / 100).

What is your opinion to solve this problem? I appreciate your answers.

5 months ago ยท Juan Pablo Isaza
Answer question
Find remote jobs