I need to convert a base 10 number to a base 16 a store it in an array. I need to check if the number is nonnegative and representable as a 5digit hex number. Return true if so and reuturn false and leave the hex array unmodified.
My problem is that I used the math library. Can anyone give me any tips as too how to calculate this and leave my array unmodified if false?
bool makeHex(long number, int hex[])
{
int x,y,z,r;
int numOfHexDigits;
int maxDigits = 5;
numOfHexDigits = (int)(log((double)number) / log(16.0));
numOfHexDigits++;
if (numOfHexDigits == 5)
{
x = number;
for(int i = 0; i < maxDigits; i++)
{
y = x/16;
z = y*16;
r = x-z;
x = y;
hex[i] = r;
}
returntrue;
}
elsereturnfalse;
}
....when converted to baes 16, how many numbers will fit in the array.
So, if I entered in 39619 (which is 9ac3 in base 16) it will return the value 4. I make this calculation beforehand because once it goes through the loop then it modifies the array (and I dont want that to happen).
In this case I had t use the math lib math.h to make that calculation. My question to those with more evolved logic is.... how would you make the same calculation without using the math lib?
bool makeHex(unsignedlong number, int hex[])
{
if (number > 0xFFFFF)
returnfalse;
int x, y, z, r;
for(int i = 0; i < maxDigits; i++)
{
y = x/16;
z = y*16;
r = x-z;
x = y;
hex[i] = r;
}
returntrue;
}
Galik's code was right but the comparison with 0 is unnecessary, you can just make number an unsigned long instead of signed.
I understand the first part "number >=0" but I'm not sure the second part will work.
This number: 0xFFFFF is in hexadecimal format. So it is the largest possible five digit hexadecimal number. Therefore as long as your number is less than or equal to it then when it is converted it can not exceed it in number of digits.