简体   繁体   English

Java:将带符号的Int_32(十六进制)转换为Int

[英]Java: Convert signed Int_32 (hex) to Int

I've got a signed int_32 value (FFFFFFFC) what's representing -4 我有一个带符号的int_32值(FFFFFFFC),它表示-4

If I try to convert it by ... 如果我尝试通过...转换

long x = Long.parseLong("FFFFFFFC", 32);
System.out.println("X: " + x);

... I'll get "X: 532021755372" instead of -4. ...我将得到“ X:532021755372”而不是-4。 How could I convert it as a signed value? 如何将其转换为有符号值?

You get an incorrect result because 32 represents the numeric base , not the number of bits in the result. 您得到的结果不正确,因为32代表数字基 ,而不是结果中的位数。 You are parsing the string as a base-32 number (ie a number in a numbering system that uses digits 0..9 and letters A..V, not 0..9 and A..F. 您正在将字符串解析为以32为基数的数字(即,在编号系统中使用数字0..9和字母A..V而不是0..9和A..F的数字。

To parse the number correctly, use Long.parseLong("FFFFFFFC", 16); 要正确解析数字,请使用Long.parseLong("FFFFFFFC", 16); , and cast the result to int , which is a 32-bit number: ,并将结果转换为int ,这是一个32位数字:

int x = (int)Long.parseLong("FFFFFFFC", 16);
System.out.println("X: " + x); // Prints X: -4

Demo. 演示。

if FFFFFFFC represents -4 it is int, not long, parse it like this 如果FFFFFFFC表示-4,则为int,不长,像这样解析

int x = Integer.parseUnsignedInt("FFFFFFFC", 16);

and you will get -4 你会得到-4

Try this 尝试这个

int x= new BigInteger("FFFFFFFC", 16).intValue();
System.out.println("X: " + x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM