位运算检查加减乘除溢出

位运算

&

|

~

^

<<

>>

>>>

检查溢出

最贵的溢出代价:一行代码蒸发了¥6,447,277,680 人民币!
以减法为例:
A - B = C

A B 正常结果 溢出结果
>0 >0 不会溢出
<0 <0 不会溢出
>0 <0 >0 <0
<0 >0 <0 >0
0 - 不会溢出
- 0 不会溢出

只有当A、B异号才有可能出现溢出,则

1
2
3
4
5
6
7
8
9
public static long safeSubtract(long val1, long val2) {
long diff = val1 - val2;
// If there is a sign change, but the two values have different signs...
if ((val1 ^ diff) < 0 && (val1 ^ val2) < 0) {
throw new ArithmeticException
("The calculation caused an overflow: " + val1 + " - " + val2);
}
return diff;
}

更多示例参考:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
* Copyright 2001-2005 Stephen Colebourne
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joda.time.field;

import org.joda.time.DateTimeField;
import org.joda.time.DateTimeFieldType;
import org.joda.time.IllegalFieldValueException;

/**
* General utilities that don't fit elsewhere.
* <p>
* FieldUtils is thread-safe and immutable.
*
* @author Stephen Colebourne
* @since 1.0
*/
public class FieldUtils {

/**
* Restricted constructor.
*/
private FieldUtils() {
super();
}

//------------------------------------------------------------------------
/**
* Negates the input throwing an exception if it can't negate it.
*
* @param value the value to negate
* @return the negated value
* @throws ArithmeticException if the value is Integer.MIN_VALUE
* @since 1.1
*/
public static int safeNegate(int value) {
if (value == Integer.MIN_VALUE) {
throw new ArithmeticException("Integer.MIN_VALUE cannot be negated");
}
return -value;
}

/**
* Add two values throwing an exception if overflow occurs.
*
* @param val1 the first value
* @param val2 the second value
* @return the new total
* @throws ArithmeticException if the value is too big or too small
*/
public static int safeAdd(int val1, int val2) {
int sum = val1 + val2;
// If there is a sign change, but the two values have the same sign...
if ((val1 ^ sum) < 0 && (val1 ^ val2) >= 0) {
throw new ArithmeticException
("The calculation caused an overflow: " + val1 + " + " + val2);
}
return sum;
}

/**
* Add two values throwing an exception if overflow occurs.
*
* @param val1 the first value
* @param val2 the second value
* @return the new total
* @throws ArithmeticException if the value is too big or too small
*/
public static long safeAdd(long val1, long val2) {
long sum = val1 + val2;
// If there is a sign change, but the two values have the same sign...
if ((val1 ^ sum) < 0 && (val1 ^ val2) >= 0) {
throw new ArithmeticException
("The calculation caused an overflow: " + val1 + " + " + val2);
}
return sum;
}

/**
* Subtracts two values throwing an exception if overflow occurs.
*
* @param val1 the first value, to be taken away from
* @param val2 the second value, the amount to take away
* @return the new total
* @throws ArithmeticException if the value is too big or too small
*/
public static long safeSubtract(long val1, long val2) {
long diff = val1 - val2;
// If there is a sign change, but the two values have different signs...
if ((val1 ^ diff) < 0 && (val1 ^ val2) < 0) {
throw new ArithmeticException
("The calculation caused an overflow: " + val1 + " - " + val2);
}
return diff;
}

/**
* Multiply two values throwing an exception if overflow occurs.
*
* @param val1 the first value
* @param val2 the second value
* @return the new total
* @throws ArithmeticException if the value is too big or too small
* @since 1.2
*/
public static int safeMultiply(int val1, int val2) {
long total = (long) val1 * (long) val2;
if (total < Integer.MIN_VALUE || total > Integer.MAX_VALUE) {
throw new ArithmeticException("Multiplication overflows an int: " + val1 + " * " + val2);
}
return (int) total;
}

/**
* Multiply two values throwing an exception if overflow occurs.
*
* @param val1 the first value
* @param val2 the second value
* @return the new total
* @throws ArithmeticException if the value is too big or too small
* @since 1.2
*/
public static long safeMultiply(long val1, int val2) {
switch (val2) {
case -1:
if (val1 == Long.MIN_VALUE) {
throw new ArithmeticException("Multiplication overflows a long: " + val1 + " * " + val2);
}
return -val1;
case 0:
return 0L;
case 1:
return val1;
}
long total = val1 * val2;
if (total / val2 != val1) {
throw new ArithmeticException("Multiplication overflows a long: " + val1 + " * " + val2);
}
return total;
}

/**
* Multiply two values throwing an exception if overflow occurs.
*
* @param val1 the first value
* @param val2 the second value
* @return the new total
* @throws ArithmeticException if the value is too big or too small
*/
public static long safeMultiply(long val1, long val2) {
if (val2 == 1) {
return val1;
}
if (val1 == 1) {
return val2;
}
if (val1 == 0 || val2 == 0) {
return 0;
}
long total = val1 * val2;
if (total / val2 != val1 || val1 == Long.MIN_VALUE && val2 == -1 || val2 == Long.MIN_VALUE && val1 == -1) {
throw new ArithmeticException("Multiplication overflows a long: " + val1 + " * " + val2);
}
return total;
}

/**
* Divides the dividend by the divisor throwing an exception if
* overflow occurs or the divisor is zero.
*
* @param dividend the dividend
* @param divisor the divisor
* @return the new total
* @throws ArithmeticException if the operation overflows or the divisor is zero
*/
public static long safeDivide(long dividend, long divisor) {
if (dividend == Long.MIN_VALUE && divisor == -1L) {
throw new ArithmeticException("Multiplication overflows a long: " + dividend + " / " + divisor);
}
return dividend / divisor;
}

/**
* Casts to an int throwing an exception if overflow occurs.
*
* @param value the value
* @return the value as an int
* @throws ArithmeticException if the value is too big or too small
*/
public static int safeToInt(long value) {
if (Integer.MIN_VALUE <= value && value <= Integer.MAX_VALUE) {
return (int) value;
}
throw new ArithmeticException("Value cannot fit in an int: " + value);
}

/**
* Multiply two values to return an int throwing an exception if overflow occurs.
*
* @param val1 the first value
* @param val2 the second value
* @return the new total
* @throws ArithmeticException if the value is too big or too small
*/
public static int safeMultiplyToInt(long val1, long val2) {
long val = FieldUtils.safeMultiply(val1, val2);
return FieldUtils.safeToInt(val);
}

//-----------------------------------------------------------------------
/**
* Verify that input values are within specified bounds.
*
* @param value the value to check
* @param lowerBound the lower bound allowed for value
* @param upperBound the upper bound allowed for value
* @throws IllegalFieldValueException if value is not in the specified bounds
*/
public static void verifyValueBounds(DateTimeField field,
int value, int lowerBound, int upperBound) {
if ((value < lowerBound) || (value > upperBound)) {
throw new IllegalFieldValueException
(field.getType(), Integer.valueOf(value),
Integer.valueOf(lowerBound), Integer.valueOf(upperBound));
}
}

/**
* Verify that input values are within specified bounds.
*
* @param value the value to check
* @param lowerBound the lower bound allowed for value
* @param upperBound the upper bound allowed for value
* @throws IllegalFieldValueException if value is not in the specified bounds
* @since 1.1
*/
public static void verifyValueBounds(DateTimeFieldType fieldType,
int value, int lowerBound, int upperBound) {
if ((value < lowerBound) || (value > upperBound)) {
throw new IllegalFieldValueException
(fieldType, Integer.valueOf(value),
Integer.valueOf(lowerBound), Integer.valueOf(upperBound));
}
}

/**
* Verify that input values are within specified bounds.
*
* @param value the value to check
* @param lowerBound the lower bound allowed for value
* @param upperBound the upper bound allowed for value
* @throws IllegalFieldValueException if value is not in the specified bounds
*/
public static void verifyValueBounds(String fieldName,
int value, int lowerBound, int upperBound) {
if ((value < lowerBound) || (value > upperBound)) {
throw new IllegalFieldValueException
(fieldName, Integer.valueOf(value),
Integer.valueOf(lowerBound), Integer.valueOf(upperBound));
}
}

/**
* Utility method used by addWrapField implementations to ensure the new
* value lies within the field's legal value range.
*
* @param currentValue the current value of the data, which may lie outside
* the wrapped value range
* @param wrapValue the value to add to current value before
* wrapping. This may be negative.
* @param minValue the wrap range minimum value.
* @param maxValue the wrap range maximum value. This must be
* greater than minValue (checked by the method).
* @return the wrapped value
* @throws IllegalArgumentException if minValue is greater
* than or equal to maxValue
*/
public static int getWrappedValue(int currentValue, int wrapValue,
int minValue, int maxValue) {
return getWrappedValue(currentValue + wrapValue, minValue, maxValue);
}

/**
* Utility method that ensures the given value lies within the field's
* legal value range.
*
* @param value the value to fit into the wrapped value range
* @param minValue the wrap range minimum value.
* @param maxValue the wrap range maximum value. This must be
* greater than minValue (checked by the method).
* @return the wrapped value
* @throws IllegalArgumentException if minValue is greater
* than or equal to maxValue
*/
public static int getWrappedValue(int value, int minValue, int maxValue) {
if (minValue >= maxValue) {
throw new IllegalArgumentException("MIN > MAX");
}

int wrapRange = maxValue - minValue + 1;
value -= minValue;

if (value >= 0) {
return (value % wrapRange) + minValue;
}

int remByRange = (-value) % wrapRange;

if (remByRange == 0) {
return 0 + minValue;
}
return (wrapRange - remByRange) + minValue;
}

//-----------------------------------------------------------------------
/**
* Compares two objects as equals handling null.
*
* @param object1 the first object
* @param object2 the second object
* @return true if equal
* @since 1.4
*/
public static boolean equals(Object object1, Object object2) {
if (object1 == object2) {
return true;
}
if (object1 == null || object2 == null) {
return false;
}
return object1.equals(object2);
}

}