在我正在开发的应用程序中,首先,我执行从十进制值到十六进制字符串的转换。
例如,我将int值 -100000 转换为它的十六进制值:
hex_value = Integer.toHexString (-100000)
我明白了:
hex_value = FFFE7960
现在,我需要进行逆转换。我得到 FFFE7960 十六进制值,我需要再次将其转换为 -100000 ,为此我使用:
int_value = Integer.parseInt(hex_value,16)
但不是 -100000 ,而是 4294867296 。
因此,我得到一个无符号值,而不是获取有符号的int值,导致我的应用程序出错。
如何才能获得所需的价值?
更新 - 完整代码
这是我通过蓝牙收到的字符串:
s = "2b 00 ff fe 79 60"
使用StringTokenizer我将其拆分:
StringTokenizer tokens = new StringTokenizer(s," ");
String one = tokens.nextToken();
String two = tokens.nextToken();
String three = tokens.nextToken();
String four = tokens.nextToken();
String five = tokens.nextToken();
String six = tokens.nextToken();
received_hexValue = three + four + five + six;
所以, received_hexValue =“fffe7960”
现在,我进行了我需要的转换:
int_value_receive = (int)Long.parseLong(received_hexValue, 16);
int_value_receive = -200000 - int_value_receive;
newIntValue = (int_value_receive * 100) / (200000 * (-1));
在第一行中,当从十六进制转换为int时,调试器会抛出一个Long.invalidLong(String)错误,并在logcat中显示错误注释:java.lang.NullPointerException
答案 0 :(得分:2)
尝试使用以下代码。
String hex_value = Integer.toHexString(-100000);
Log.d("Home", "Hex : " + hex_value);
int int_value = (int) Long.parseLong(hex_value, 16);
Log.d("Home", "Int : " + int_value);
此代码首先会创建长值4294867296
,然后将-100000
作为输出返回。
修改强>
您的代码就像
String s = "2b 00 ff fe 79 60";
StringTokenizer tokens = new StringTokenizer(s, " ");
String one = tokens.nextToken();
String two = tokens.nextToken();
String three = tokens.nextToken();
String four = tokens.nextToken();
String five = tokens.nextToken();
String six = tokens.nextToken();
String received_hexValue = three + four + five + six;
Log.d("Home", "Hex : " + received_hexValue);
//to get sub string of your length, pass start and end offset
Log.d("Home", "SubString Hex : " +received_hexValue.substring(0, 8));
int int_value_receive = (int) Long.parseLong(received_hexValue, 16);
Log.d("Home", "Old Int : " + int_value_receive);
int_value_receive = -200000 - int_value_receive;
Log.d("Home", "Int : " + int_value_receive);
int newIntValue = (int_value_receive * 100) / (200000 * (-1));
Log.d("Home", "New Int : " + newIntValue);
<强>输出强>
09-03 16:22:37.421:DEBUG / Home(28973):Hex:fffe7960
09-03 16:22:37.421:DEBUG / Home(28973):Old Int:-100000
09-03 16:22:37.421:DEBUG / Home(28973):Int:-100000
09-03 16:22:37.421:DEBUG / Home(28973):New Int:50