简体   繁体   中英

How do I convert a hex string to a signed int value in Java?

In my computer organization class we were assigned a program. I am stuck on one thing. I have the value 7FF as a string and I need to convert it to a signed int. I can get it to an unsigned int. I get the value 2047. The correct value should be -1.

Right now here is what I have:

int x = Integer.parseInt("7FF", 16);

I have tried casting it with a short but that did not do anything. Any help would be appreciated! Thank you.

Edit: So my main question is, how can I produce an output of -1 with the hex string "7FF"?

To parse a hex string to an 11-bit signed value, you can use the following method.

The algorithm was taken from Bit Twiddling Hacks by Sean Eron Anderson.

public static int parseElevenBits(String hex) {
    return Integer.parseInt(hex, 16) << 21 >> 21;
}

Test

System.out.println(parseElevenBits("400"));
System.out.println(parseElevenBits("401"));
System.out.println(parseElevenBits("7FE"));
System.out.println(parseElevenBits("7FF"));
System.out.println(parseElevenBits("0"));
System.out.println(parseElevenBits("1"));
System.out.println(parseElevenBits("3FE"));
System.out.println(parseElevenBits("3FF"));

Output

-1024
-1023
-2
-1
0
1
1022
1023

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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