wchar_t * to short int conversion

时间:2015-03-02 10:18:49

标签: c++ c++11

第三方类中的一个函数返回一个持有资源ID的wchar_t*(我不知道它为什么使用wchar_t *类型)我需要将此指针转换为short int < / p>

这个方法,使用AND运算符为我工作。但似乎不是正确的方法。有没有正确的方法来做到这一点?

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

4 个答案:

答案 0 :(得分:3)

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

您也可以将short int b替换为auto b,并将从右侧表达式的类型推断为short int

答案 1 :(得分:2)

它将资源ID返回为wchar_t*,因为这是Windows用于承载资源标识符的数据类型。可以通过数字ID或名称来标识资源。如果是数字,则指针本身包含以低16位编码的实际ID号。否则,它是指向内存中其他位置的以null结尾的字符串的普通指针。有一个IS_INTRESOURCE()宏来区分哪个是实际情况,例如:

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

答案 2 :(得分:1)

您的代码是wchar_t *s;吗?

我使用

更明确地进行转换
short int b = reinterpret_cast<short int>(s);

答案 3 :(得分:0)

如果它符合您的应用需求,我建议使用具有固定n位的数据类型,例如uint16_t。使用short int意味着您只能确定您的变量至少有16位。另一个问题:为什么不使用unsigned short int而不是(signed)short int?

一般而言,了解确切的nr位会使事情更容易预测,并且更容易确切地知道在投射或使用位掩码时会发生什么。