L
L
Levorukij52018-07-26 00:20:12
C++ / C#
Levorukij5, 2018-07-26 00:20:12

What exactly happens in Arduino when you try to write too large a number?

What happens at a deep level when you try to write too large a number to an integer variable? That the size of a variable is limited to 16 bits and one of them is reserved for the sign is understandable. Where the range of values ​​comes from is also clear. But what exactly happens when you try to go beyond this range?
Why is it that, when calculating powers of two, at some point the minimum value, -32768, is displayed, and then only zeros? What happens with other operations with too large numbers?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-07-26
@jcmvbkbc

Where the range of values ​​comes from is also clear. But what exactly happens when you try to go beyond this range?
Why is it that, when calculating powers of two, at some point the minimum value, -32768, is displayed, and then only zeros?

Is it clear ?
2^0 == 0b0000000_00000001 == 1 (16 LSBs)
...
2^14 == 0b01000000_00000000 == 16384 (16 LSBs)
...
2^15 - 1 == 0b01111 LSB11_11111111 == 32767 (16)
2^15 == 0b100000_00000000 == -32768 (16 LSBs)
2^15 + 1 == 0b100000_00000001 == -32767 (16 LSBs)
...
2^16 - 1 == 0b11111111_11111111 == -1 (16 LSBs)
2^16 == 0b1_00000000_00000000 == 0 (16 LSBs) 2
^16 + 1 == 0b1_00000000_00000001 == 1 (16 LSBs)
Undefined behavior if the value type is signed. The compiler can optimize whatever it wants.
If the value type is unsigned, the result is truncated to the width of the result data type.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question