If I understand correctly you want something like
http://en.wikipedia.org/wiki/Binary-coded_decimal, but for numerals with radix 0xD.
I want to respectfully suggest that you should reserve a contiguous range for error values. For example, all negative values could be errors. I say this, because your approach is pain, and all this packing/unpacking that you have to do is less efficient for both the client code (to detect errors) and the implementation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
using namespace std;
int main()
{
unsigned int n = 0x1234;
cout << hex;
for (unsigned int counter = 0; counter < n; /*++counter is applied in the body*/)
{
cout << counter << endl;
{
unsigned int carry = 1; //we increment with 1, so 1 is the initial carry
unsigned int prefix = counter; //start with all nibbles in the queue
while (carry > 0)
{
if ((prefix & 0xf) < 0xc) //no carry
{
break;
}
else //perform carry
{
carry <<= 4; //position the carry on the next nibble
prefix >>= 4; //pop the current nibble from the queue
}
}
counter &= ~(carry - 1); //zero all nibbles below the carry
counter += carry; //apply the current carry
}
}
}
|
I think that this code is portable, but let the other guys comment.
I also though of using unions, as in
1 2 3 4 5
|
union
{
unsigned char bytes[sizeof(unsigned int)];
unsigned int packed;
}
|
or even using bit fields for the nibbles. I mean, this nibble processing is way too heavy. But bit-fields are not portable according to the standard, and the union thing is actually not portable either, although that can be discussed.
What I mean is, I don't know if there is truly portable alternative to my code, but do you have any idea how much processing per single increment that does? :)
Best Regards
EDIT: fixed the code to handle properly carry from the most significant nibble (overflow)