十六进制值乘法溢出

时间:2013-08-26 00:42:29

标签: java android

我试图将2个Hex值相乘,并接收Hex值作为输出。我目前接受一个包含十六进制值的字符串,将其转换为一个整数乘以,然后将其转换回十六进制字符串。

这是乘以十进制(基数为10)的示例。

//this works for all cases
//operand1, operand2 & displayValue are strings that should be any value from 0-F
long solutionInt = 0;
int currentBase = 10;
solutionInt = Integer.parseInt(operand1, currentBase) * Integer.parseInt(operand2, currentBase);
displayValue = Integer.toString(Integer.valueOf(Long.toString(solutionInt)).intValue());

这是我遇到麻烦的地方,乘以十六进制(基数为16)

//this does NOT work for larger numbers (that would overflow)
//operand1, operand2 & displayValue are strings that should be and value from 0-F               
long solutionInt = 0;
int currentBase = 16;           
solutionInt = Integer.parseInt(operand1, currentBase) * Integer.parseInt(operand2, currentBase);
displayValue = Integer.toHexString(Integer.valueOf(Long.toString(solutionInt)).intValue());

当乘以会导致溢出的较大十六进制值(即:0xFFFFFFFF * 0xFFFFFFF)时,我的Android应用程序崩溃并收到以下错误:

FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity

我需要displayValue来保存一个十六进制字符串(如果转换为数字)将是大小为int。我不确定是否存在导致此错误的某种溢出,或其他与android中的活动有关的内容。

1 个答案:

答案 0 :(得分:0)

为什么不使用BigDecimal。可以从十六进制字符串构造一个大小数,然后使用multiple方法。

请参阅http://www.velocityreviews.com/forums/t126470-no-hexadecimal-parsing-formatting-for-biginteger.html