Author Topic: 32bit multiply - having a brain fart  (Read 309 times)

megatron-uk

  • Full Member
  • ***
  • Posts: 219
32bit multiply - having a brain fart
« 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:

Code: [Select]
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

  • Hero Member
  • *****
  • Posts: 14142
  • Fuck Elmer.
    • Incessant Negativity Software
Re: 32bit multiply - having a brain fart
« Reply #1 on: February 02, 2014, 11:18:58 AM »
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.
[Fri 19:34]<nectarsis> been wanting to try that one for awhile now Ope
[Fri 19:33]<Opethian> l;ol huge dong

I'm a max level Forum Warrior.  I'm immortal.
If you're not ready to defend your claims, don't post em.

megatron-uk

  • Full Member
  • ***
  • Posts: 219
Re: 32bit multiply - having a brain fart
« Reply #2 on: February 02, 2014, 08:15:12 PM »
(sound of hand slapping forehead)

Of course:

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

« Last Edit: February 02, 2014, 11:25:07 PM by megatron-uk »

megatron-uk

  • Full Member
  • ***
  • Posts: 219
Re: 32bit multiply - having a brain fart
« Reply #3 on: February 03, 2014, 06:21:37 AM »
Works perfectly, thank you!  ](*,)

Also simplified it, slightly, to the following:

Code: [Select]
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;
}
}