Alternative to using math.h

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?

Here is a piece of my code:

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
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;
		}
		return true;	
	}
	else
		return false;
	
}
I assume this would do it:
1
2
3
4
	if(number >= 0 && number <= 0xFFFFF)
	{

	}
Last edited on
Well that's not going to work out. I understand the first part "number >=0" but I'm not sure the second part will work.

In my code... what this calculates (based on the number yu entered):

1
2
	numOfHexDigits = (int)(log((double)number) / log(16.0));
	numOfHexDigits++;


....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?
Like this I think:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool makeHex(unsigned long number, int hex[])
{
        if (number > 0xFFFFF)
                return false;
        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;
	}

	return true;	
}

Galik's code was right but the comparison with 0 is unnecessary, you can just make number an unsigned long instead of signed.
dlugo wrote:
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.
Last edited on
Topic archived. No new replies allowed.