Link to home
Start Free TrialLog in
Avatar of Ingo Foerster
Ingo Foerster

asked on

Problem with numeric value in cpp

In a code part of a software that I got to update I found a the line

TypeAndTimeZone = UINT16( 1 << 12 | uint16(timeDiff/60));

timeDiff has the negative value -7200.0000

TypeAndTimeZone will get the value: 65416
What kind of numeric value is this because I expected -120.
If I will do
TypeAndTimeZone = TypeAndTimeZone * -1 I will get 120 instead of 65416.

Is 65416 a negative numeric value? Or is there an error to get this as a negative value?
Avatar of ozo
ozo
Flag of United States of America image

uint16 is unsigned 16 bit integer.
-120 is 0xffffffffffffff88
truncating that to 16 bits gets 0xff88, which as an unsigned value = 65416
What kind of numeric value is this because I expected -120.

the type is unsigned short integer with a range from 0 to 65535  or hex 0x0000 to 0xffff

the 65535 (or 0xffff) is equal to -1 if the value was viewed as a signed short integer. that is because the highest bit 15 is used as sign bit. if bit 15 is set, the numbers become negative.

we have that signed short and unsigned short are identical from 0 to 32767. 32767 is 0x7fff in hex and 7fff means that bit 0 to bit 14 are 1 and only bit 15 is 0. if we increment 0xffff by 1 we get 0x8000 where all bits beside of bit 15  are 0 . this number is 32768 for unsigned short and -32768 when interpreted as signed short. the next number is 32769 resp. -32767 signed. finally we have 65535 for unsigned short is equal to (65536-1) is equal to -1 signed

therefore 65416 = 65536 - 120  would be -120 if looked on as signed short int.

Sara
Avatar of Roger Alcindor
Roger Alcindor

As explained completely by Sara,
Your expression  UINT16( 1 << 12 | uint16(timeDiff/60)); will never return a negative value as UINT16 makes it an unsigned integer.

If you want to get the negative value that you expect then your expression should be changed to INT16( 1 << 12 | UINT16(timeDiff/60));
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.