我创建了自己的函数,将一个String转换为BCD中的等效bytes []。然后我将此字节发送到DataOutputStram(使用需要byte []数组的write方法)。问题在于数字字符串“8000000000000000”。看这个:
First two characters: "8" "0"
"8" = "1000"
"0" = "0000"
binary value of the first byte = "10000000"
Exception in thread "Thread-3" java.lang.NumberFormatException: Value out of range. Value:"10001000" Radix:2
你看到了问题吗?我试图在字节[]中保存“128”十进制值,但由于字节范围值介于-128和127之间,因此不可能。我该怎么办?
这是我的功能代码:
public class UtilityBCD
{
//Decimal: 0 1 2 3 4 5 6 7 8 9
//BCD: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001
private static final String zero = "0000";
private static final String one = "0001";
private static final String two = "0010";
private static final String three = "0011";
private static final String four = "0100";
private static final String five = "0101";
private static final String six = "0110";
private static final String seven = "0111";
private static final String eight = "1000";
private static final String nine = "1001";
public static byte[] numericStringToBCD(String value)
{
int len = value.length();
String values[] = new String[len];
//WE CREATE AN ARRAY WITH THE BCD VALUE OF EACH CHARACTER
for ( int i = 0; i < len; i++ )
{
values[i] = toBCDValue(value.charAt(i));
System.out.println(values[i]);
}
System.out.println("\nEnd of values\n");
//WE DETERMINATE IF THE STRING IS ODD AND WE CREATE
//THE NEW ARRAY WITH THE HELF OF SIZE OF THE ORIGINAL
//STRING
int iterator;
boolean isOdd = len % 2 != 0;
iterator = len/2;
String values2[] = new String[iterator];
System.out.println("ITERATOR: " + iterator);
//WE SET THE NEW ARRAY WITH THE COUPLES OF BCD'S VALUES
int j = 0;
for ( int i = 0; i < iterator;i ++)
{
if ( isOdd && i == (iterator - 1) )
values2[i] = values[j];
else
{
values2[i] = values[j] + values[j + 1];
j++;
}
}
//FINALLY WE CREATE AN ARRAY OF BYTE'S AND SAVE THE EACH
byte values3[] = new byte[iterator];
for ( int i = 0; i < iterator; i++ )
{
System.out.println("DEBUG BCD : " + values2[i]);
values3[i] = Byte.parseByte(values2[i], 2); //HERE IS THE PROBLEM
}
return values3;
}
private static String toBCDValue(char character)
{
String bcdValue = null;
switch(character)
{
case '0': bcdValue = zero; break;
case '1': bcdValue = one; break;
case '2': bcdValue = two; break;
case '3': bcdValue = three; break;
case '4': bcdValue = four; break;
case '5': bcdValue = five; break;
case '6': bcdValue = six; break;
case '7': bcdValue = seven; break;
case '8': bcdValue = eight; break;
case '9': bcdValue = nine; break;
}
return bcdValue;
}
}
问候!
答案 0 :(得分:1)
好的,我找到了解决方案,我简单地改变了这一行:
values3[i] = Byte.parseByte(values2[i], 2); //HERE IS THE PROBLEM
现在这一项工作完美无缺!
values3[i] = (byte) Integer.parseInt(values2[i], 2);
如果有人想解释这一点,我将不胜感激。
问候!
答案 1 :(得分:0)
我可以想到几个选项:
Byte
以外的类型(例如Integer
)。Byte
中的值。假设您的值在0到255之间,减去128会将其置于允许的范围内(即使用Byte.parseByte(values2[i], 2)-128
)。根据您的应用程序,您可能需要进行其他转换。