32bit int * 32bit int = 64 bit int?

In other words, does this work as expected?

int32 i = INT_MAX-1; int64 j = i * i; 

or do I need to transfer me to 64 bit first?

+6
c ++ integer-overflow
source share
5 answers

You need to give at least one of the operands for multiplication. At the point the multiplication is done, the system does not know that you plan to assign int64.

(If int64 is actually not a native int type for your particular system, which seems unlikely)

+17
source share

It depends on what int32 and int64 are.

In short, all integers are advanced, at least to the value of "int" (which may be 64 bits) before any arithmetic operations and the size of a larger operand for binary operators if it has a greater rank than int.

As a result, the use of an expression (regardless of whether it is stored more widely) does not affect the promotion of the constituent parts of the expression.

+7
source share

The main answer: no, he will not do what you want.
But he does what is expected.

Two things to note about math operations:

  • Both operands will be of the same type.
  • The resulting type will be the same as the input.

If the compiler notices a mismatch between the operands, it converts one of the operands so that both match (see What variables should I use when performing mathematical operations in C / C ++? ). Note. This is done in isolation from what happens to the result.

+3
source share

For two numbers a, b and each number, len_a and len_b are used.

Your output data type requires at least len_a and len_b.

In the above code, you have two 31-bit numbers (because INT_MAX - 1 = 0x7FFFFFFE uses 31 bits), and you will need to map one of them to int64_t, because it will do 32-bit multiplication and overflow before int64_t.


The number of bits required for fixed-point multiplication:

 len_output = howManyBits( a * b ) = len_a + len_b 

A quick example to show the rule above:

 a = 7 len_a = 3 b = 7 len_b = 3 c = a * b = 49 ( decimal ) = 0x31 ( hex ) len_c = howManyBits( 0x31 ) = 6 

You can write a function to count the bits. Or, if you just want to quickly check your sanity to confirm this, use something like Windows Calc, which converts the number to binary and counts the bits used.

0
source share

See: 14. Mixed use of simple integer types and memsize types. http://www.viva64.com/art-1-2-599168895.html

0
source share

All Articles