开发者

Passing HRESULT as a string on command line

开发者 https://www.devze.com 2023-01-22 06:09 出处:网络
I have a need to pass in an HRESULT value to a program as a command line argument. I had intended to do so by passing the hex value, e.g.:

I have a need to pass in an HRESULT value to a program as a command line argument. I had intended to do so by passing the hex value, e.g.:

>receiver.exe 0x80048836

I'm trying to convert this string representation back into an HRESULT using wcstol, eg:

HRESULT hr = wcstol(argv[2], NULL, 16);

However, the value of the original HRESULT is usually greater than LONG_MAX, so in the line above hr ends up as 0x7fffffff.

So, two questions:

  1. I thought HRESULTS were just 32-bit integers? So I'm not sure how I'm getting back an HRESULT greater than LONG_MAX. It seems to work fine in the originating program, though (i.e. the HRESULT doesn't overflow).

  2. Is there a way to get around the LONG_MAX restriction of wcstol? Maybe another version of t开发者_运维问答he function that matches up with whatever size integer the HRESULT actually is?

Thanks!


Check out wcstoul. http://msdn.microsoft.com/en-us/library/5k9xb7x1(v=VS.80).aspx The HRESULT does fit in 32 bits, but with the example you gave it uses the most significant bit, which is considered to act like a sign bit for signed integers. Using wcstoul will fit it into an unsigned long.

LONG_MAX is 0x7FFFFFFF, the highest that can fit in the 31 least significant bits, leaving the top bit cleared, but ULONG_MAX goes up to 0xFFFFFFFF because it is unsigned.


0x80048836 is greater than LONG_MAX for your system (2147483647L) which is (0x7FFFFFFF). According to msdn "when the representation would cause an overflow, in which case it returns LONG_MAX or LONG_MIN"

So in your case you get LONG_MAX returned as your result.

the actual function return type is declared as long wcstol(...). long is not necessarily 32 bits in size, that will depend on your system.

In this case the return type is signed and 32 bit so the largest signed integer that will fit in 32 bits is 7FFFFFFF.
00000000 to 7FFFFFFF is positive from 0 to LONG_MAX FFFFFFFF to 8000001 is negative from -1 to LONG_MIN

Incidentally I believe "HRESULT hr = wcstol..." would be incorrect since the return type of wcstol is (signed) long , but HRESULT is ULONG (unsigned long). This might be a problem depending on how you use that data.

0

精彩评论

暂无评论...
验证码 换一张
取 消