简体   繁体   English

C中跨平台数据类型的库

[英]Library for cross platform datatypes in C

Is there a C (not C++, Boost etc.) library for providing cross platform datatypes ? 是否有一个C(不是C ++,Boost等)库提供跨平台数据类型?

To elaborate, I want to store an int in a file in a 32-bit linux machine, read the file and the same int from a 64-bit windows machine. 详细地说,我想将int存储在32位linux机器的文件中,从64位Windows机器读取文件和相同的int Is this possible ? 这可能吗 ?

Update: I do not want to use sqlite or some kind of database either. 更新:我也不想使用sqlite或某种数据库。 I want a library which can help me in using the data types throughout my code. 我想要一个可以帮助我在整个代码中使用数据类型的库。

If all you want to do is store 32 bits signed integers, just decide on a format, for example big endian. 如果您只想存储32位带符号整数,则只需确定格式即可,例如big endian。 You can then write the serialisation/deserialisation yourself: 然后,您可以自己编写序列化/反序列化:

void write_int32_be (int32_t i, FILE *f)
{
  uint8_t buf[4];

  buf[0] = ((uint32_t)i >> 24);
  buf[1] = ((uint32_t)i >> 16) & 0xFF;
  buf[2] = ((uint32_t)i >> 8) & 0xFF;
  buf[3] = (uint32_t)i & 0xFF;
  fwrite (buf, 4, 1, f);
}

int32_t read_int32_be (FILE *f)
{
  uint8_t buf[4];

  fread (buf, 4, 1, f);

  return ((uint32_t)buf[0] << 24) |
         ((uint32_t)buf[1] << 16) |
         ((uint32_t)buf[2] << 8) |
          (uint32_t)buf[3];
}

If you need a variety of types, use a library like tpl , Eet , Avro , protobuf-c or an implementation of a standard like XDR , JSON , or ASN.1 . 如果需要各种类型,请使用tplEetAvroprotobuf-c之类的库,或使用XDRJSONASN.1之类的标准实现。 If you have large numerical data sets use something like HDF or NetCDF . 如果您有大量的数字数据集,请使用HDFNetCDF之类的东西。

If your compiler(s) know about C99 standard then you can just use int32_t 如果您的编译器了解C99标准,则可以使用int32_t

http://en.wikipedia.org/wiki/C_data_types#Fixed_width_integer_types IMHO your OS should have the same endianness. http://en.wikipedia.org/wiki/C_data_types#Fixed_width_integer_types恕我直言,您的操作系统应具有相同的字节序。 Windows and Linux on x86 and x86_64 are both little-endian, so it should work. x86和x86_64上的Windows和Linux都是低位优先的,因此应该可以使用。 http://en.wikipedia.org/wiki/Endianness#Endianness_and_operating_systems_on_architectures http://zh.wikipedia.org/wiki/Endianness#Endianness_and_operating_systems_on_architectures

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM