1

怎么做呢?另外,有没有简单的方法可以做到这一点?使用像 Boost 之类的库?

4

3 回答 3

4

写出 int 的 DataOutputStream 写出一个 4 字节的 int,高字节在前。读入 char*,重新解释,如果需要转换字节顺序,请使用 ntohl。

ifstream is;
is.open ("test.txt", ios::binary );
char* pBuffer = new char[4];

is.read (pBuffer, 4);
is.close();

int* pInt = reinterpret_cast<int*>(pBuffer);
int myInt = ntohl(*pInt); // This is only required if you are on a little endian box
delete [] pBuffer;
于 2009-07-23T03:41:57.283 回答
2

唯一的跨平台方法是逐字节(即charby char)读取它,并从中构建一个整数。您想使用long, 因为int不能保证足够宽以容纳 32 位值。我假设您已将字节读入char[4]此处的数组中(其他答案已经演示了如何做到这一点):

char bytes[4];
...
long n = (long(bytes[0]) << 24) | (long(bytes[1]) << 16) |
         (long(bytes[2]) << 8)  |  long(bytes[3])
于 2009-07-23T03:55:04.107 回答
0

想法:

  1. 将其作为直接二进制读取,然后根据需要转换/解释字节。因此,如果 Java 为 int 写出 4 个字节,那么您读入 4 个字节。如果有任何字节序要更改,则执行此操作,然后将字节数组转换(或复制)到 c++ int
  2. 如果您可以更改 Java 代码,则可以将其写成 C++ 可以读取的常见内容,例如 UTF-8 文本或 ascii,或者 Google Protocol Buffers 格式或其他格式。
于 2009-07-23T03:35:25.410 回答