gpt4 book ai didi

c++ - int to short 分配失败

转载 作者:行者123 更新时间:2023-11-28 00:54:17 24 4
gpt4 key购买 nike

我在尝试将 short 提升为 int 时遇到了一些奇怪的行为,其中高 2 个字节在提升后为 0xFFFF。据我所知,高位字节应始终保持为 0。请参阅以下代码:

    unsigned int test1 = proxy0->m_collisionFilterGroup;
unsigned int test2 = proxy0->m_collisionFilterMask;
unsigned int test3 = proxy1->m_collisionFilterGroup;
unsigned int test4 = proxy1->m_collisionFilterMask;

if( test1 & 0xFFFF0000 || test2 & 0xFFFF0000 || test3 & 0xFFFF0000 || test4 & 0xFFFF0000 )
{
std::cout << "test";
}

一旦cout被命中,相关变量的值是:

Strange Promotion

注意两个突出显示的值。我还查看了对我来说也很好的反汇编:

Disassembly

我的软件是针对使用 VS 2008 SP1 编译的 x64。我还链接了 Bullet Physics 2.80 的开箱即用版本。代理对象是项目符号对象。

代理类定义如下(删减部分功能):

    ///The btBroadphaseProxy is the main class that can be used with the Bullet broadphases. 
///It stores collision shape type information, collision filter information and a client object, typically a btCollisionObject or btRigidBody.
ATTRIBUTE_ALIGNED16(struct) btBroadphaseProxy
{

BT_DECLARE_ALIGNED_ALLOCATOR();

///optional filtering to cull potential collisions
enum CollisionFilterGroups
{
DefaultFilter = 1,
StaticFilter = 2,
KinematicFilter = 4,
DebrisFilter = 8,
SensorTrigger = 16,
CharacterFilter = 32,
AllFilter = -1 //all bits sets: DefaultFilter | StaticFilter | KinematicFilter | DebrisFilter | SensorTrigger
};

//Usually the client btCollisionObject or Rigidbody class
void* m_clientObject;
short int m_collisionFilterGroup;
short int m_collisionFilterMask;
void* m_multiSapParentProxy;
int m_uniqueId;//m_uniqueId is introduced for paircache. could get rid of this, by calculating the address offset etc.

btVector3 m_aabbMin;
btVector3 m_aabbMax;

SIMD_FORCE_INLINE int getUid() const
{
return m_uniqueId;
}

//used for memory pools
btBroadphaseProxy() :m_clientObject(0),m_multiSapParentProxy(0)
{
}

btBroadphaseProxy(const btVector3& aabbMin,const btVector3& aabbMax,void* userPtr,short int collisionFilterGroup, short int collisionFilterMask,void* multiSapParentProxy=0)
:m_clientObject(userPtr),
m_collisionFilterGroup(collisionFilterGroup),
m_collisionFilterMask(collisionFilterMask),
m_aabbMin(aabbMin),
m_aabbMax(aabbMax)
{
m_multiSapParentProxy = multiSapParentProxy;
}
}
;

我以前从未遇到过这个问题,只是在升级到 64 位并集成 bullet 后才开始遇到这个问题。我遇到的唯一问题是涉及 bullet 的地方,所以我怀疑问题与此有关,但我仍然非常困惑是什么导致原始类型之间的分配无法按预期运行。

谢谢

最佳答案

您正在请求从有符号到无符号的转换。这是非常直截了当的:

  • 您的源值为 -1。由于类型是 short int,在您的平台上有位 0xFFFF

  • 目标类型是unsigned int-1 不能表示为 unsigned int,但转换规则由标准定义:选择与 -1 modulo 2N,其中N是无符号类型的值位数。

    在您的平台上,unsigned int 有 32 个值位,因此 -1 模 232 的模表示是 0xFFFFFFFF

如果您自己想像规则在哪里应用,您会想要结果 0x0000FFFF,即 65535,并且与 -1 没有任何明显或有用的关联。

如果您确实想要这种转换,您必须手动对短类型执行模块化环绕:

short int mo = -1;
unsigned int weird = static_cast<unsigned short int>(mo);

简而言之:C++ 是关于,而不是关于表示

关于c++ - int to short 分配失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12418939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com