[英]Understanding bitwise operations and their effects
我试图在下面的代码中了解按位运算符的目的:
#define BIT8 unsigned char
#define BIT16 unsigned short
#define MEAN_SIZE (sizeof(BIT16) * 32)
void *Alloc16Address(void** pAlignedStart, unsigned long ulBytes) // ulBytes=2048
{
void *pBuffer = new BIT8 [ulBytes + 16];
*pAlignedStart = (void*)((((unsigned long)pBuffer >> 4) << 4) + 16);
return pBuffer;
}
后来这段代码给出了访问冲突:
f(std::ostream& stream)
{
BIT16* m_pMeans, x;
int iSize = 32;
x = (BIT16*) Alloc16Address((void**)&m_pMeans,MEAN_SIZE*iSize);
stream.read((char*)m_pMeans, MEAN_SIZE*iSize); // <<<< access volation
}
我知道用尽文件可能会产生错误,但以前这适用于相同的代码和文件 ,唯一的变化是从旧的WIN7计算机迁移到新的WIN10计算机。 至少我想排除按位操作线是罪魁祸首。 该代码能否受某些环境的影响而改变?
与按位运算符无关。 问题是在64位Windows上, unsigned long
只有32位。 该代码可能在WIN32上运行正常。
更改:
*pAlignedStart = (void*)((((unsigned long)pBuffer >> 4) << 4) + 16);
至:
*pAlignedStart = (void*)((((uintptr_t)pBuffer >> 4) << 4) + 16);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.