我使用的是 C++11 及更高版本,我在问自己获取像 std::uint16_t
这样的数据类型所需的字节数来发送长度不可知的协议(protocol)是否安全.更精确地调用 sizeof(std::uint16_t)
是否安全,我可以假设它总是 2 吗? std::int16_t
呢?
最佳答案
Safe way to get number of bytes for a data type in C++
那将是 sizeof
运算符。
More precise is it safe to call sizeof(std::uint16_t) and can I assume that this is always 2?
没有。当字节为 8 位时,您只能依赖它。
What about std::int16_t?
相同。
对于网络通信,您可能需要知道一种类型有多少个八位字节。可以像这样安全地计算它:sizeof(std::uint16_t) * (CHAR_BIT/8)
,对于 std::uint16_t
将为 2。请注意,并非所有系统都必须具有 std::uint16_t
类型。
关于c++ - 在 C++ 中获取数据类型字节数的安全方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63178387/