I'm struggling with a really weird situation that I can't explain.
Basically I don't understand why results of modulus or division between two hex numbers are wrong (I'm using C
).
I have a variable time
which is a 32bit unsigned int
and it's initialized to 0 and then other two 32bit unsigned ints
, div
and res
, both initialized to 0 too.
if (time > 0x1388) {
div = time / 0x1388;
res = time - (0x1388 * div);
}
This chunk of code should act as the modulus operator between time
and 0x1388
. Time
is a variable which gets incremented all around my program and when it's value is greater than 0x1388
, I need its remainder to do other calculations.
This is an example of calculated value that are wrong... Let's suppose time
is 0x1770
, which is greater than 0x1388
. The division between 0x1770
and 0x1388
should be 0x1
(div
) with a reminder of 0x3E8
(res
).
The problem is that after executing this code, div
is always 0x0FFFFF
instead of 0x1
and res
gets a really weird value.
I already tried to use the modulus but the result is the same. Can someone explain me what's going on?
Maybe is it related to the fact that I'm using unsigned ints
? If so, can you please tell me what operations I need to be careful of when using unsigned ints
?
EDIT: Trying to add some more code...
file1.c
unsigned int res = 0, div = 0, time = 0; // global variables
unsigned int valueChecker() {
if (time > 0x1388) {
div = time / 0x1388;
res = time - (0x1388 * div);
}
return res;
}
This function is called periodically after a specific amount of time
fileB.c
extern unsigned int time;
void calculate() {
// do some stuff
time += getHEXTime(); // this function has been supplied and return time as an HEX number
// do other stuff
}
This function is called by the main several times, between other calculation (which doesn't involve time
, div
or res
).
I'd be so grateful if someone can help me!