当两个 16 位有符号数据相乘时,结果的大小应该是多少?
我遇到过一个与嵌入式系统和C/C++相关的面试问题。问题是:
如果我们将 2 个有符号(2 的补码)16 位数据相乘,结果数据的大小应该是多少?
我已经开始尝试使用两个有符号 4 位相乘的示例,因此,如果我们将 +7
和 -7
相乘,我们最终会得到 - 49
,需要 7 位。但是,我无法建立一般关系。
我想我需要深入理解二进制乘法才能解决这个问题。
I have faced an interview question related to embedded systems and C/C++. The question is:
If we multiply 2 signed (2's complement) 16-bit data, what should be the size of resultant data?
I've started attempting it with an example of multiplying two signed 4-bit, so, if we multiply +7
and -7
, we end up with -49
, which requires 7 bits. But, I could not formulate a general relation.
I think I need to understand binary multiply deeply to solve this question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,n 位有符号整数包含 -(2^(n-1))..+(2^(n-1))-1 范围内的值。
例如,对于 n=4,范围为 -(2^3)..(2^3)-1 = -8..+7
乘法结果的范围为 -8*+7 .. -8* -8 = -56..+64。
+64 大于 2^6-1 - 它是 2^6 = 2^(2n-2) !您需要 2n-1 位来存储这样的正整数。
除非您正在进行专有编码(请参阅下一段) - 您将需要 2n 位:
1 位用于符号,2n-1 位用于乘法结果的绝对值。
如果 M 是乘法的结果,则可以存储 -M 或 M-1。这可以为您节省 1 位。
First, n bits signed integer contains a value in the range -(2^(n-1))..+(2^(n-1))-1.
For example, for n=4, the range is -(2^3)..(2^3)-1 = -8..+7
The range of the multiplication result is -8*+7 .. -8*-8 = -56..+64.
+64 is more than 2^6-1 - it is 2^6 = 2^(2n-2) ! You'll need 2n-1 bits to store such POSITIVE integer.
Unless you're doing proprietary encoding (see next paragraph) - you'll need 2n bits:
One bit for the sign, and 2n-1 bits for the absolute value of the multiplication result.
If M is the result of the multiplication, you can store -M or M-1 instead. this can save you 1 bit.
这将取决于上下文。在 C/C++ 中,所有小于
int
的中间值都会提升为int
。因此,如果int
大于 16 位,则结果将是一个带符号的 32 位整数。但是,如果将其分配回 16 位整数,它将被截断,仅留下新数字的二进制补码的底部 16 位。
因此,如果您对“结果”的定义是紧随乘法之后的中间值,那么答案就是
int
的大小。如果将大小定义为将其存储回 16 位变量后,则答案是 16 位整数类型的大小。This will depend on context. In C/C++, all intermediates smaller than
int
are promoted toint
. So ifint
is larger than 16-bits, then the result will be a signed 32-bit integer.However, if you assign it back to a 16-bit integer, it will truncate leaving only bottom 16 bits of the two's complement of the new number.
So if your definition of "result" is the intermediate immediately following the multiply, then the answer is the size of
int
. If you define the size as after you've stored it back to a 16-bit variable, then answer is the size of the 16-bit integer type.