将INT32BE宏转换为 constexpr 是否正确?

Is this conversion of an INT32BE macro to a constexpr correct?

本文关键字:是否 constexpr INT32BE 转换      更新时间:2023-10-16

>我有以下宏,并希望将其转换为constexpr,因为显然这是一种更好的方法:

#define INT32BE(x) (x[0] << 24 | x[1] << 16 | x[2] << 8 | x[3])

尝试:

template <typename T>
constexpr auto Int32BE(T array [])
{
return array[0] << 24 | array[1] << 16 | array[2] << 8 | array[3];
}

这旨在按以下方式使用:

const auto address = Int32BE(data.Address);

Address的定义如下:

UCHAR Address[4];

它确实按预期工作,但我不完全确定应该如何编写。

问题:

这是从正确写入的数组中读取 32 位整数constexpr吗?

我不能从"语言律师"的角度说话,但是您给出的constexpr在以下代码中毫无警告地编译,同时包含MSVCclang-cl

#include <stdio.h>
template <typename T>
constexpr auto Int32BE(T array[]) {
return array[0] << 24 | array[1] << 16 | array[2] << 8 | array[3];
}
int main() {
unsigned char Address[4] = { 0x22, 0xAA, 0x11, 0xBB };
const auto address = Int32BE(Address);
printf("%08Xn", address);
return 0;
}

此外,输出是期望值(22AA11BB(。