Java将int转换为十六进制并再次返回 [英] Java converting int to hex and back again

查看:98
本文介绍了Java将int转换为十六进制并再次返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码...

  int Val = -32768; 
字符串十六进制= Integer.toHexString(Val);

这相当于 ffff8000

  int FirstAttempt = Integer.parseInt(Hex,16); //错误Invalid Int
int SecondAttempt = Integer.decode(0x+ Hex); //错误Invalid Int

所以,最初它会将值-32768转换为十六进制字符串ffff8000,但它不能将十六进制字符串转换回整数。



.Net 正如我所料,并且返回-32768



我知道我可以写我自己的小方法来转换这个自己,但我只是想知道如果我错过了一些东西,或者如果这真的是一个错误?

解决方案

它会溢出,因为数字是负数。



试试这个,它会工作:

  int n =(int)Long.parseLong(ffff8000,16); 


I have the following code...

int Val=-32768;
String Hex=Integer.toHexString(Val);

This equates to ffff8000

int FirstAttempt=Integer.parseInt(Hex,16); // Error "Invalid Int"
int SecondAttempt=Integer.decode("0x"+Hex);  // Error "Invalid Int"

So, initially, it converts the value -32768 into a hex string ffff8000, but then it can't convert the hex string back into an Integer.

In .Net it works as I'd expect, and returns -32768.

I know that I could write my own little method to convert this myself, but I'm just wondering if I'm missing something, or if this is genuinely a bug?

解决方案

It overflows, because the number is negative.

Try this and it will work:

int n = (int) Long.parseLong("ffff8000", 16);

这篇关于Java将int转换为十六进制并再次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆