android - 从十六进制字符串到有符号整数

标签 android int hex

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

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

最佳答案

尝试使用以下代码。

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: 调试/Home(28973): 十六进制: fffe7960
09-03 16:22:37.421:调试/主页(28973):旧整数:-100000
09-03 16:22:37.421: 调试/主页(28973): Int : -100000
09-03 16:22:37.421:调试/主页(28973):新整数:50

关于android - 从十六进制字符串到有符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18589357/

相关文章:

java - 我需要生成一个十六进制表示的 32 位随机且唯一的数字

arrays - 如何将固定长度的十六进制 rune 数组转换为单个整数

android - startActivityForResult(Intent intent, int requestCode, Bundle options) 如何检索额外的 bundle 选项?

android - 尝试在空对象引用上调用接口(interface)方法 'boolean com.google.common.util.concurrent.ListenableFuture.cancel(boolean)'

android - Android的 "Hello, Testing"教程中的JUnit NullPointerException错误

c++ - 在使用 ceil 的 C++ 中,除法不起作用?

c - 十六进制值和普通类型的区别

android - 当前日期应该在 android 中增加 12 小时

java - 打印浮点值

c++ - 函数重载中的 int 和 float