I have been assigned with a task to perform unsigned multiplication using signed multiplier. Despite multiple attempts, I couldn't get it. Is it possible to do this?
Code:
#include <stdio.h>
int main()
{
// Must be short int
short int a=0x7fff;
short int b=0xc000;
unsigned int res1;
signed int res2;
//unsigned multiplier
res1= (unsigned short int) a * (unsigned short int) b;
//signed multiplier
res2= (short int) a * (short int) b;
printf("res1: 0x%x %d \n res2: 0x%x %d\n",res1,res1,res2,res2);
return 0;
}
This is the code provided.
Current Output:
res1: 0x5fff4000 1610563584
res2: 0xe0004000 -536854528
Expected Output:
res1: 0x5fff4000 1610563584
res2: 0x5fff4000 1610563584
Working Code:
#include<stdio.h>
#include<conio.h>
int main()
{
short int a = 0x7fff;
short int b = 0x3000;
unsigned int unsignedRes;
signed int signedRes;
unsigned int ourRes;
// Unsigned Multiplier
unsignedRes = (unsigned short int) a * (unsigned short int) b;
// Signed Multiplier
signedRes = (short int) a * (short int) b;
// Our Code using SIgned Multiplier
ourRes = ((short int)a & ~(0xffffu << 16))*((short int)b & ~(0xffffu << 16));
printf("Expected: 0x%x\nSigned: 0x%x\nResult: 0x%x",unsignedRes,signedRes,ourRes);
getch();
return 0;
}
The assignment
short int b=0xc000;alone is already implementation defined (vid.: ISO/IEC 9899:2018 6.3.1.3 p. 3) and would need to be done in two partsb = b1 * 2^15 + b0 = 0x1*2^15 + 0x4000(assumingSHRT_MAX + 1 == 32768). If you do both in two parts like that and understand the assignment in such a way that the result is an unsigned data type and doa*b == (a1 * 2^15 + a0) * (b1 * 2^15 + b0)by usingunsigned int ret2for the result andsigned inttemporary variables for the rest.Assuming that the input is restricted to the capabilities of an
unsigned short int(unsignedbecause of0xc000) and that all types must be signed types with the exception of the output:The assignment is rather under-defined, to keep it polite, but as I do not know if it is your fault, the teacher's fault or a bad zoom-connection I tried to give you a couple of directions. If it wasn't wat was expected you should at least be able to ask the right questions now.