Skip to content

Hexadecimal

Intro

On the web we use hexadecimal to represent colors, e.g. green: 008000, teal: 008080, navy: 000080).

The program should handle invalid hexadecimal strings.

Task

Convert a hexadecimal number, represented as a string (e.g. "10af8c"), to its decimal equivalent using first principles (i.e. no, you may not use built-in or external libraries to accomplish the conversion).

The Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include "hexadecimal.h"
#include "test/catch.hpp"
#include <cstdint>

namespace hexadecimal {
std::uint32_t convert(std::string test) {
std::uint32_t result{};
for (auto c : test) {
    if (c >= '0' && c <= '9') {
    result <<= 4;
    result |= (c - '0');
    } else if (c >= 'a' && c <= 'f') {
    result <<= 4;
    result |= (c - 'a') + 10;
    } else {
    return 0;
    }
}
return result;
}
} // namespace hexadecimal
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <cstdint>
#include <string>
#if !defined(HEXADECIMAL_H)
#define HEXADECIMAL_H
#include "string"
namespace hexadecimal {
    std::uint32_t convert(std::string);
}  // namespace hexadecimal

#endif // HEXADECIMAL_H

Last update: February 11, 2021

Comments