PCEngineFans.com - The PC Engine and TurboGrafx-16 Community Forum
Tech and Homebrew => Turbo/PCE Game/Tool Development => Topic started by: megatron-uk on February 02, 2014, 10:14:22 AM
-
So I've got this function that I *thought* was working correctly for multiplying a 32bit number by an 8bit number:
mul_int32_int8(int32_result, int32, int8)
char* int32_result;
char* int32;
char int8;
{
char i;
char v;
int old_v;
v = 0;
for (i = 4; i > 0; --i){
/* multiply and add overflow from last loop*/
old_v = (int32[i] * int8) + v;
/* store lsb */
int32[i] = old_v & 0xff;
/* store msb as overflow for next loop */
v = (old_v >> 8) & 0xff;
}
if ((int32[0] + v) < int32[0]){
int32[0] = int32[0] + v;
/* overflow */
memcpy(int32_result, int32, 4);
return 1;
} else {
int32[0] = int32[0] + v;
memcpy(int32_result, int32, 4);
return 0;
}
}
The test case is:
int32 = 348 (0x0000015c)
int8 = 8
I should be seeing 2784 (0x00000AE0), but I see 2790 (0x00000AE6) which results in my sector calculations going haywire. My original code used a brain-dead routine of calling my add_int32() function multiple times (like I said, brain dead), but I coded this faster multiply routine instead.
Can anyone see where I've gone wrong? It's late and I don't think I'm quite seeing it!
-
I'm guessing int32 is a 4 byte array, in which case doing your first iteration of your for loop won't work since a 4 byte array goes from 0 to 3
You're indexing it with i which starts at 4. That's not going to work.
-
(sound of hand slapping forehead)
Of course:
(i=3; i>0; i--)
That's what I get for coding before going to bed.
-
Works perfectly, thank you! ](*,)
Also simplified it, slightly, to the following:
mul_int32_int8(int32_result, int32, int8)
char* int32_result;
char* int32;
char int8;
{
char i;
char v;
int old_v;
v = 0;
for (i = 3; i > 0; --i){
/* multiply and add overflow from last loop*/
old_v = (int32[i] * int8) + v;
/* store lsb */
int32_result[i] = old_v & 0xff;
/* store msb as overflow for next loop */
v = (old_v >> 8) & 0xff;
}
int32_result[0] = (int32[0] * int8) + v;
if (int32[0] > int32_result[0]){
/* overflow */
return 1;
} else {
return 0;
}
}