unsigned int类型的函数返回负数 [英] Function of type unsigned int returns negative number
问题描述
哇我以为我认识我的C ++,但这是奇怪的
Wow I thought I knew my C++ but this is weird
这个函数返回一个unsigned int,所以我认为这意味着我永远不会得到一个负数返回吗?
This function returns an unsigned int so I thought that means I will never get a negative number returned right?
该函数确定UTC前面或后面多少小时。所以对我来说,我在澳大利亚,悉尼,所以我是+10 GMT,这意味着我是UTC = LocalTime +(-10)。因此,GetTimeZoneInformation正确地确定我是-10。
The function determines how many hours ahead or behind of UTC you are. So for me I'm in Australia, Sydney so I am +10 GMT which means I am UTC = LocalTime + (-10). Therefore the GetTimeZoneInformation correctly determines I am -10.
但是我的函数返回一个unsigned int,所以不应该返回10不是-10?
unsigned int getTimeZoneBias()
{
TIME_ZONE_INFORMATION tzInfo;
DWORD res = GetTimeZoneInformation( &tzInfo );
if ( res == TIME_ZONE_ID_INVALID )
{
return (INT_MAX/2);
}
return (unsigned int(tzInfo.Bias / 60)); // convert from minutes to hours
}
TCHAR ch[200];
_stprintf( ch, _T("A: %d\n"), getTimeZoneBias()); // this prints out A: -10
debugLog += _T("Bias: ") + tstring(ch) + _T("\r\n");
推荐答案
以下是我的想法:
tzInfo.Bias
的值实际上为-10。 ( 0xFFFFFFF6
)
在大多数系统上,将带符号的整数转换为大小相同的无符号整数对表示无效。
The value of tzInfo.Bias
is actually -10. (0xFFFFFFF6
)
On most systems, casting a signed integer to an unsigned integer of the same size does nothing to the representation.
因此,函数仍然返回 0xFFFFFFF6
。
'重新打印为一个有符号整数。所以它打印 -10
。如果您将它作为无符号整数打印,则可能会得到 4294967286
。
But when you print it out, you're printing it back as a signed integer. So it prints-10
. If you printed it as an unsigned integer, you'll probably get 4294967286
.
要做的是得到时间差的绝对值。所以你想把这个-10转换成10.你应该返回 abs(tzInfo.Bias / 60)
。
What you're probably trying to do is to get the absolute value of the time difference. So you want to convert this -10 into a 10. In which you should return abs(tzInfo.Bias / 60)
.
这篇关于unsigned int类型的函数返回负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!