[英]Cross-platform endian conversion
I've written this code to convert between host and network endianness and found the implementations for both directions is the same.我编写了这段代码来在主机和网络字节序之间进行转换,发现两个方向的实现是相同的。 Is that right?
那正确吗?
template<typename T>
T be_to_host(T val)
{
T outval = 0;
std::size_t len = sizeof(T);
char *data = reinterpret_cast<char*>(&outval);
// network endian (big) to host endian
for (int i = 0; i < len; i++)
data[i] = (val >> ((len - i - 1) * 8)) & 0xFF;
return outval;
}
template<typename T>
T host_to_be(T val)
{
// works both ways on any platform
return be_to_host<T>(val);
}
I've convinced myself this code is OK but I've always seen different implementations for each direction so I can't shake that feeling that I'm missing something.我已经说服自己这段代码没问题,但我总是看到每个方向都有不同的实现,所以我无法摆脱那种我错过了什么的感觉。 The fact the 'val' is interpreted as host endianness makes this code bi-direction, right?
“val”被解释为主机字节序这一事实使此代码双向,对吗?
Thanks谢谢
如果字节序不同,那么在任一方向上的任务是颠倒字节的顺序,所以是的,在任一方向上的实现是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.