Nayana Adassuriya
Nayana Adassuriya

Reputation: 24766

wchar_t* to short int conversion

One of the function in a 3rd party class return awchar_t* that holding a resource id (I don't know why it uses wchar_t* type ) I need to convert this pointer to short int

This method, using AND operator works for me. but it seems like not the correct way. is there any proper way to do this?

wchar_t* s;
short int b = (unsigned long)(s) & 0xFFFF;

Upvotes: 0

Views: 1552

Answers (4)

Remy Lebeau
Remy Lebeau

Reputation: 596672

It returns the resource ID as a wchar_t* because that is the data type that Windows uses to carry resource identifiers. Resources can be identified by either numeric ID or by name. If numeric, the pointer itself contains the actual ID number encoded in its lower 16 bits. Otherwise it is a normal pointer to a null-terminated string elsewhere in memory. There is an IS_INTRESOURCE() macro to differentiate which is the actual case, eg:

wchar_t *s = ...;
if (IS_INTRESOURCE(s))
{
    // s is a numeric ID...
    WORD b = (WORD) s;
    ...
}
else
{
    // s is a null-terminated name string
    ...
}

Upvotes: 2

Erik Alapää
Erik Alapää

Reputation: 2703

If it fits your application needs, I suggest using a data type with a fixed nr of bits, e.g. uint16_t. Using short int means you only know for sure your variable has at least 16 bits. An additional question: Why do you not use unsigned short int, instead of (signed) short int?

In general, knowing the exact nr of bits make things a little more predictable, and makes it easier to know exactly what happens when you cast or use bitmasks.

Upvotes: 0

Jim Oldfield
Jim Oldfield

Reputation: 674

wchar_t* s; // I assume this is what you meant
short int b = static_cast<short int>(reinterpret_cast<intptr_t>(s))

You could also replace short int b with auto b, and it will be deduced as short int from the type of the right-hand expression.

Upvotes: 4

Andrey Derevyanko
Andrey Derevyanko

Reputation: 560

Did you mean in your code wchar_t *s;?

I'd do the conversion more explicit using

short int b = reinterpret_cast<short int>(s);

Upvotes: 1

Related Questions