macro_controller
macro_controller

Reputation: 1519

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.

#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. What is the best and safest way to do that?

Upvotes: 0

Views: 341

Answers (2)

RbMm
RbMm

Reputation: 33744

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. if work with signed types, say SSIZE_T nValueToConvert and SHORT wConvertedValue, task become more complex, separate signed bit create problems here. 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

Upvotes: 1

sg7
sg7

Reputation: 6298

Conversion may not give a proper result. The type sizes are different. Check this:

Window Data Types

SIZE_T Unsigned integral type; defined as:

typedef ULONG_PTR SIZE_T;

WORD A 16-bit unsigned integer. The range is 0 through 65535 decimal. This type is declared in WinDef.h as follows:

  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");
}

Upvotes: 1

Related Questions