简体   繁体   English

安全地将SIZE_T转换为WORD

[英]Safely convert SIZE_T to WORD

In my C code, I want to convert SIZE_T WINAPI type, in either 32/64 bit system to a WORD WINAPI type. 在我的C代码中,我想将32/64位系统中的SIZE_T WINAPI类型转换为WORD WINAPI类型。

#include <Windows.h>
SIZE_T nValueToConvert;
WORD wConvertedValue;

In case that nValueToConvert is too big for WORD type I want to know abot it and raise an error. 如果nValueToConvert对于WORD类型而言太大,我想知道它是什么,然后引发错误。 What is the best and safest way to do that? 最好和最安全的方法是什么?

exist many ways do this. 存在很多方法可以做到这一点。 for example we can use next code: 例如,我们可以使用下一个代码:

if ((wConvertedValue = (WORD)nValueToConvert) == nValueToConvert)
{
    DbgPrint("convert ok\n");
}
else
{
    DbgPrint("too big for WORD\n");
}

however this is valid only for unsigned types - both SIZE_T and WORD is unsigned. 但是,这仅对无符号类型有效SIZE_TWORD都是无符号的。 if work with signed types, say SSIZE_T nValueToConvert and SHORT wConvertedValue , task become more complex, separate signed bit create problems here. 如果使用带符号的类型,请说SSIZE_T nValueToConvertSHORT wConvertedValue ,任务将变得更加复杂,单独的带符号位会在此处产生问题。 i think try truncate and check can be done next way: 我认为尝试截断并检查可以通过以下方式完成:

BOOL Truncate(SSIZE_T nValueToConvert, SHORT* pwConvertedValue)
{
    SHORT wConvertedValue;

    if (0 > nValueToConvert)
    {
        wConvertedValue = -(wConvertedValue = ((SHORT)-nValueToConvert));
    }
    else
    {
        wConvertedValue = (SHORT)nValueToConvert;
    }

    *pwConvertedValue = wConvertedValue;

    return wConvertedValue == nValueToConvert;
}

Truncate return true when SSIZE_T nValueToConvert in range [-0x8000, 0x7FFF] , otherwise false SSIZE_T nValueToConvert在范围[-0x8000, 0x7FFF]Truncate返回true,否则返回false

Conversion may not give a proper result. 转换可能不会给出正确的结果。 The type sizes are different. 类型大小不同。 Check this: 检查一下:

Window Data Types 窗口数据类型

SIZE_T Unsigned integral type; SIZE_T无符号整数类型; defined as: 定义为:

typedef ULONG_PTR SIZE_T;

WORD A 16-bit unsigned integer. WORD 16位无符号整数。 The range is 0 through 65535 decimal. 范围是0到65535(十进制)。 This type is declared in WinDef.h as follows: WinDef.h中声明此类型,如下所示:

  typedef unsigned short WORD;

But if you really want to compare them than 但是,如果您真的想比较它们,

if( nValueToConvert > 65535 ) (
{
    DbgPrint("Conversion is not safe\n");
}
else
{
    DbgPrint("conversion is OK\n");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM