2

在我正在开发的应用程序中,首先,我将十进制值转换为十六进制字符串。

例如,我将 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));

在第一行,当从十六进制转换为整数时,调试器向我抛出 Long.invalidLong(String) 错误,并在 logcat 中显示错误注释:java.lang.NullPointerException

4

1 回答 1

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);

此代码将首先创建 long 值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): 十六进制: 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

于 2013-09-03T10:11:20.823 回答