Given a hex value of 0x80 (supplied as a uint16_t) in c++ how would I extract the digits into an int variable. I don't want to convert the hex to int, rather I want to extract the digits as an int, so for example, for 0x80 i want an int of 80, not 128, or for 0x55 I want 55 not 85, etc.
uint16_t hex = 0x80;
uint8_t val = ???; // Needs to be 80
Numbers with hex-only digits will never happen. I.e. input will only consist of decimal digits.
E.g. 0x08, 0x09, 0x10, 0x11, 0x12, etc.
Since you say that the hex number never contains 'a', 'b', etc. this code should do the trick:
output
Explanation
A 16 bit hex number in = 0xWZYX is calculated as
When doing
when doing
When doing
The pattern is then repeated for each digit.
An alternative implementation using shift
For a 16 bit unsigned integer it can be okay to write out the four lines. However, if you wanted a similar function for a larger unsigned int, it may be better to do a loop to keep the code more compact and maintainable.
64 bit solution using a loop
output