c++ - 在 C++ 中获取数据类型字节数的安全方法

标签 c++ c++11 uint16

我使用的是 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/

相关文章:

C++子类访问主类变量

c++ - 无法使用 ifstream 将 txt 文件的最后一部分写入 cout

c++ - 元组 View 的元素类型

C 将 uint16 写入文件出现错误

c - uint_16t转换后uint8_t的值

python - uint16 图像的重新缩放/规范化混淆?

c++ - "Connecting"SDL_Surface 到 shared_ptr

c++ - POD 的 WinAPI union 双关语到基本类型 : Implementation dependent or standard compliant?

c++ - 编译时等效于 std::accumulate()

c++ - 无法为 unique_ptr 返回类型返回 nullptr