32bit multiply - having a brain fart

Started by megatron-uk, 02/02/2014, 06:14 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

megatron-uk

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!

Arkhan Asylum

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.
This "max-level forum psycho" (:lol:) destroyed TWO PC Engine groups in rage: one by Aaron Lambert on Facebook "Because Chris 'Shadowland' Runyon!," then the other by Aaron Nanto "Because Le NightWolve!" Him and PCE Aarons don't have a good track record together... Both times he blamed the Aarons in a "Look-what-you-made-us-do?!" manner, never himself nor his deranged, destructive, toxic turbo troll gang!

megatron-uk

#2
(sound of hand slapping forehead)

Of course:

(i=3; i>0; i--)
That's what I get for coding before going to bed.

megatron-uk

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;
}
}