zoukankan      html  css  js  c++  java
  • c++ detect && solve integer overflow

    以uint为例,当计算过程中(比如9999^6)产生大于UINT_MAX(2^32 - 1)的值的时候,编译时会产生integer overflow,即数值溢出,最后的结果也被截断.

    1.如何检测 :https://www.quora.com/How-do-I-prevent-integer-overflow-in-C++(有墙)

    贴上里面提供的示例代码:

    #include <iostream>
    #include <cstdlib>
    #include <climits>
    int main() {
      int x = 0x70000000;
      int y = 0x70000000;
      bool underflow = false;
      bool overflow  = false;
      if ((x > 0) && (y > INT_MAX - x)) overflow = true;
      if ((x < 0) && (y < INT_MIN - x))  underflow = true;
       
      if(overflow) {
        std::cerr << "overflow will occur
    ";
        exit(-1);
      }
      
      if(underflow) {
        std::cerr << "underflow will occur
    ";
        exit(-1);
      }
      int z =  x + y;  // UH OH!
      std::cout << z << "
    ";
    }

     2.如何解决:可以使用数组或者字符串模拟,例如使用std::string模拟乘法计算.只要内存够,多大的数都存的下(这里类似pure python的处理方式:使用pure python做运算,不会产生overflow,但是使用Numpy则会有overflow的问题,具体可参考:https://mortada.net/can-integer-operations-overflow-in-python.html)

    string bigmul(string a, string b) {
    	int size = a.size() + b.size();
    	char* res = new char[size];
    	memset(res, a.size() + b.size(), 0);
    	for (int i = b.size() - 1; i >= 0; i--) {
    		for (int j = a.size() - 1; j >= 0; j--) {
    			res[i+j+1] += (b[i] - '0')* (a[j] - '0');
    			res[i+j] += res[i+j+1]/10;
    			res[i+j+1] = res[i+j+1]%10;
    		}
    	}
    	for (int i = 0; i < size; i++) {
    		res[i] += '0';
    	}
    	return  res[0] == '0' ? string(res+1) : string(res);
    }
    

      

  • 相关阅读:
    ajax请求跨域和表单重复提交解决方案
    HTTP请求(HttpClient和PostMan)
    HTTP协议
    Oracle学习整理(二)
    oracle学习整理(一)
    MySQL的慢查询日志
    mysql索引优化
    Explain
    打好太极拳科学压腿的方法
    太极拳的压腿基本功
  • 原文地址:https://www.cnblogs.com/deepllz/p/11511013.html
Copyright © 2011-2022 走看看