Control Surface master
MIDI Control Surface library for Arduino
HexPuller.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <AH/STL/utility> // std::forward
4#include <AH/STL/vector> // std::vector
5#include <Settings/NamespaceSettings.hpp>
6#include <ctype.h> // isxdigit, tolower
7
9
24template <class CharPuller>
25class HexPuller {
26 public:
27 HexPuller(CharPuller &&puller) : puller(std::forward<CharPuller>(puller)) {}
28
35 bool pull(uint8_t &output) {
36 uint8_t input;
37 while (puller.pull(input)) {
38 // If we receive a hexadecimal digit
39 if (isxdigit(input)) {
40 (char1 ? char2 : char1) = tolower(input);
41 }
42 // If we received two hex characters
43 if (char1 && char2) {
44 output = hex2int(char1) << 4 | hex2int(char2);
45 char1 = '\0';
46 char2 = '\0';
47 return true;
48 }
49 // If we received one hex character followed by whitespace/other
50 else if (!isxdigit(input) && char1) {
51 output = hex2int(char1);
52 char1 = '\0';
53 return true;
54 }
55 }
56 return false;
57 }
58
59 private:
61 static uint8_t hex2int(char hex) {
62 return hex < 'a' ? hex - '0' : hex - 'a' + 10;
63 }
64
65 public:
66 CharPuller puller;
67
68 private:
69 char char1 = '\0';
70 char char2 = '\0';
71};
72
#define END_CS_NAMESPACE
#define BEGIN_CS_NAMESPACE
Class that parses hexadecimal ASCII text to bytes.
Definition: HexPuller.hpp:25
bool pull(uint8_t &output)
Pull out a new byte.
Definition: HexPuller.hpp:35
char char2
Definition: HexPuller.hpp:70
static uint8_t hex2int(char hex)
Convert a hexadecimal character to a 4-bit nibble.
Definition: HexPuller.hpp:61
HexPuller(CharPuller &&puller)
Definition: HexPuller.hpp:27
char char1
Definition: HexPuller.hpp:69
CharPuller puller
Definition: HexPuller.hpp:66
Print & hex(Print &printer)
Definition: PrintStream.cpp:62