简体   繁体   English

计算两个off64_t数字C ++之间的差异

[英]Calculate the difference between two off64_t numbers C++

I would like to allocate memory in order to read (whole) very large files (15-25 Gb) in my C++ program. 我想分配内存,以便在我的C ++程序中读取(整个)非常大的文件(15-25 Gb)。 I have used off64_t type to get the beginning and ending positions of the file that I want to read, which are obtained from my file using function ftello64 . 我使用了off64_t类型来获取我想要读取的文件的开始和结束位置,这些文件是使用函数ftello64从我的文件中ftello64 I would now like to get the difference between the two in a variable called size and then allocate this to a char array. 我现在想在一个名为size的变量中得到两者之间的差异,然后将其分配给char数组。 However, and despite compiling successfully, my code doesn't work properly. 但是,尽管编译成功,但我的代码无法正常工作。 I tried size = (off64_t)(end_of_mem-start_of_mem); 我试过size = (off64_t)(end_of_mem-start_of_mem); where start_of_mem and end_of_mem are both off64_t numbers but when I run my program the output is 其中start_of_memend_of_mem都是off64_t数字但是当我运行我的程序时输出是

Starting position in memory (start_of_mem):152757
Ending position in memory (end_of_mem):15808475159
Size: -1371546782

What variant type should I be using to get this right? 为了做到这一点,我应该使用哪种变体类型? Thanks in advance for your help and suggestions. 在此先感谢您的帮助和建议。

You are experiencing int down-casting from 64bit to 32bit side-effects. 您正在体验从64位到32位副作用的int。

Take a look at following experiment: 看看下面的实验:

#include <cstdint>
#include <iostream>
int main(){
  int64_t int64 = 15808475159 - 152757;
  int32_t int32 = int64;

  std::cout << "int64_t: " << int64 << "\n";
  std::cout << "int32_t: " << int32 << "\n";
}

Output: 输出:

int64_t: 15808322402
int32_t: -1371546782

Problem is the result of 15808475159 - 152757 is bigger than range of 32-bit integer. 问题是15808475159 - 152757的结果15808475159 - 152757大于32位整数的范围。 Thus due overflow it gets truncated (or mod 2^32). 因此,由于溢出它被截断(或mod 2 ^ 32)。 Then because its declared as signed 32-bit it apparently falls into the a negative range of interpretation. 然后因为它被声明为带符号的32位,它显然属于负面的解释范围。

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

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