开发者

portable unsigned long in C/C++

开发者 https://www.devze.com 2023-03-13 08:27 出处:网络
Is there portable unsigned long in C++? Is there a way to make a portable structures? On my home machine unsigned long is 8 bytes. On work machine开发者_运维知识库 its 4 bytes.
  1. Is there portable unsigned long in C++?
  2. Is there a way to make a portable structures?

On my home machine unsigned long is 8 bytes. On work machine开发者_运维知识库 its 4 bytes. When you start at home applications that are written on work there is a problem of correctness of data transmitted over the network.

Thanks.


#include <stdint.h> for the following typedefs:

  • (u)int8_t
  • (u)int16_t
  • (u)int32_t
  • (u)int64_t

While the last may or may not be available, depending on the platform.


Then don't do that. Use something like protocol buffers to transfer stuff over the network. Dumping structures into file descriptors is just a bad idea all around and you shouldn't be doing it.

You can use <stdint.h> if you have C99 compliant C implementation to make sure that the types you're using are big enough to hold the data you're sending. But even that isn't enough as your work machine and home machine might have a different endianess or any number of other problems. <stdint.h> is great for making sure your variables are big enough to hold the full range of values that they need to hold, but they are not the tool for making sure you can transfer your data over the network with no headaches.


As others have mentioned, using standard data sizes will work (e.g. from stdint.h.)

You can make structures more portable by using those data types in conjunction with some techniques used to make data structures more portable, such as data structure alignment. Typically, this involves enforcing each field to be a certain number of bytes and then copying the values into those bytes before transmitting them over a network, writing them to a file, etc.


Most platforms have typedefs called uint32_t, uint64_t, etc. that you can use. As far as I know these are not standard, but every platform I've used had them.

0

精彩评论

暂无评论...
验证码 换一张
取 消