作者lovejomi (JOMI)
看板C_and_CPP
标题[问题] 转型问题 是否符合标准?
时间Tue Mar 17 12:18:43 2020
请教各位 我有以下需求
我有一块buffer, 我想要取其中任意起始位址後面若干byte来看他的数值是不是我要的
以下是简单的我大概会用的写法
template<class T>
T* Read(char* buf, int position)
{
return reinterpret_cast<T*>(buf + position);
}
int main()
{
constexpr unsigned short TEST1 = 0x0403;
constexpr unsigned int TEST2 = 0x04030201;
char buf[] = {0x01, 0x02, 0x03, 0x04};
if ((*Read<unsigned short>(buf, 2)) == TEST1)
{
cout<<"bingo"<<endl;
}
if ((*Read<unsigned int>(buf, 0)) == TEST2)
{
cout<<"bingo2"<<endl;
}
我的问题是 因为牵扯到转型, 我实在没有很有把握说这种写法是合法的
感觉很容易就是undefined behavior....
可否请各位指教 该如何做 才是对的
隐约有个alignment的问题觉得这写法不太对
template<class TargetType>
void Read2(char* buf, int position, TargetType& t)
{
memcpy_s(&t, sizeof(TargetType), buf + position, sizeof(TargetType));
}
如果是这样写会不会比较正确
谢谢
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 39.10.158.16 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1584418725.A.560.html
※ 编辑: lovejomi (39.10.158.16 台湾), 03/17/2020 13:41:04
1F:→ aiwhat: 你是不是在找 memcmp 03/20 02:52