【发布时间】:2011-06-15 11:16:05
【问题描述】:
我有一个错误导致整数溢出,导致错误(负)时间戳被写入数据库。 代码已经修复,但我也想修复错误的数据。
我想,我可以只取错误的结果并添加 Integer.MAX_VALUE,但这似乎不起作用,它给我留下了很高的价值。我在下面的代码 sn-p 中有offset 值,但输入值没有存储。
以下代码重现了该错误:
@Test
public void testArexxConversion()
{
// The input values represent seconds since midnight, Jan 1, 2000 UTC
final int sample = 361450072; // A sample input value drawn from production
// I use the offset from the UNIX epoch to convert the vakue to UNIX seconds
final int offset = 946684800; // midnight, Jan 01 2000 UTC in UNIX seconds
// This was the buggy line in my code, the assertion will fail
long result = (sample + offset) * 1000;
// Prints 'Result is negative: -1830153280'
Assert.assertTrue(result > 0, String.format("Result is negative: %d", result));
// This is for comparison
Date dt = new Date(offset * 1000);
Assert.assertEquals(dt.getTime() + sample * 1000, result);
}
【问题讨论】:
-
另外,为什么首先会发生溢出?将上面的两个数字相加不会溢出,它是乘法,我有点预计这已经在
long上完成了,因为那是结果类型。
标签: java integer-overflow