[问题] 转型问题 是否符合标准?

楼主: lovejomi (JOMI)   2020-03-17 12:18:43
请教各位 我有以下需求
我有一块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));
}
如果是这样写会不会比较正确
谢谢
作者: aiwhat   2020-03-20 02:52:00
你是不是在找 memcmp

Links booklink

Contact Us: admin [ a t ] ucptt.com