I am not quite sure how to solve this problem, Question:
**Converts a percentage to 8bit hex string linearly
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.