[問題] 轉型問題 是否符合標準?

作者: 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