I’m a Java developer who tries to code C++ in the limited Arduino environment. Exceptions and dynamic objects are not available or have to be avoid because of memory restrictions.
My task, create a method which parses a character buffer (hex nibble) and returns a boolean value to indicate the success as well as the actual result. My attempt so far (unrelated stuff avoided):
class Parser {
unsigned char buffer[SIZE];
unsigned char index;
void parse();
bool parseHexNibble(unsigned char &result);
};
void Parser::parse() {
unsigned char result = 0;
if (!parseHexNibble(result)) {
return;
}
// do some work with result
}
bool Parser::parseHexNibble(unsigned char &result) {
unsigned char chr = buffer[index];
if (chr >= '0' && chr <= '9') {
result = chr - '0';
}
else if (chr >= 'A' && chr <= 'F') {
result = chr - 'A' + 10;
}
else {
return false;
}
index++;
return true;
}
Will this work? I’m unsure when to use * and when to use &. Is there a better solution?
There are a few ways:
The way you did it is one of them, although I recommend using a pointer rather than a reference (
*instead of&) because with references, the function call looks like you are passing a value (p.parseHexNibble(c)) while the pointer version is more clear that you may want something stored in it (p.parseHexNibble(&c)).Another option, (this one is my personal favorite) is the same thing that
getcdoes: Return anintthat either contains acharvalue (0 <= i < 256) or is-1to signal an error. In the case of no error, theintcan safely be typecast and/or stored to achar. (This assumes that it is acharin fact that you want to return.)The third way is to return a structure containing a boolean and a character (either by making your own or by using
std::pairor the like).On an unrelated note, you should be using
charrather thanunsigned charto store actual character values.unsigned charshould only be used for arbitrary raw data.