Convert hex string value to hex int - java

How can I convert the hexstring into the form of hexint below?
string hexstring = "0x67";
int hexint = 0x67;

Integer#decode can be used to convert hexadecmial string representation into its integer value:
Integer.decode("0x67");
This function automatically detects the correct base and will parse return the int 103 (0x67 = 6*16+7). If you want to manually specify a different base, see my other answer

If you only have a single byte, you can strip of the leading "0x" part and then parse as a base-16 number with Integer#parseInt:
Integer.parseInt("0x67".substring(2), 0x10);
Integer.parseInt("0x67".substring(2), 16);
0x10 is the hexadecimal representation of the decimal number 16.

String hexstring = "67";
int hexint = Integer.parseInt(hexstring, 16);
System.out.println(hexint); // 103 (decimal)
With Integer.parseInt(String s, int radix) you can parse a String to an int.
The radix is the base of that number system, in case of hex-values it is 16.

Related

Java - Hex String representation to integer Hex

I have a string as "5F2A" as Hex. I would like to convert it as int 0x5F2A.
String str = "5F2A";
int number = someOperation(str);
And the number should be (with 0x)
0x5F2A
Is it possible?
To rephrase and share what I learnt today
Map<Integer, String> map = new HashMap<>();
map.put(0x5F2A, "somevalue");
System.out.println(map.get(24362));
System.out.println(map.get(0b0101111100101010));
Would give the value somevalue for both.
No transformation required:
System.out.println("0x" + str);
And to turn an arbitrary int into HEX representation:
Integer.toHexString(intNumber);
That should be all you need to get going!
int i = 0x5F2A not really means nothing because in memory, all is in binary, it's only when you print that it matters
String str = "5F2A";
int number = Integer.parseInt(str, 16); //alows to store an int, binary 0101111100101010
System.out.println(number); //24362 (decimal by default)
System.out.println(Integer.toHexString(number)); //5f2a (hexa possible too)
By default, it prints in (binary into) decimal format, but you can print in hexa format, but int i = 0x5F2A means at 100% the same as int i = 24362
See here
Integer.parseInt(/*your String*/, 16);
16 is the radix for hexadecimal.

Signed Hexadecimal to decimal in Java

I was wondering if it's possible to convert a signed Hexadecimal (negative) to its corresponding decimal value.
I assume that you have a hexadecimal value in form of a String.
The method parseInt(String s, int radix) can take a hexadecimal (signed) String and with the proper radix (16) it will parse it to an Integer.
int decimalInt = parseInt(hexaStr, 16);
the solution above only works if you have numbers like -FFAA07BB... if you want the Two's complements you'll have to convert it yourself.
String hex = "F0BDC0";
// First convert the Hex-number into a binary number:
String bin = Integer.toString(Integer.parseInt(hex, 16), 2);
// Now create the complement (make 1's to 0's and vice versa)
String binCompl = bin.replace('0', 'X').replace('1', '0').replace('X', '1');
// Now parse it back to an integer, add 1 and make it negative:
int result = (Integer.parseInt(binCompl, 2) + 1) * -1;
or if you feel like having a one-liner:
int result = (Integer.parseInt(Integer.toString(Integer.parseInt("F0BDC0", 16), 2).replace('0', 'X').replace('1', '0').replace('X', '1'), 2) + 1) * -1;
If the numbers get so big (or small), that an Integer will have an overflow, use Long.toString(...) and Long.parseLong(...) instead.

Error Converting Hex to Float

I am trying to convert this Hex Value C2DE70A4 in Android. This is the Code that I am writing for Conversion:
try {
String hexString = "C2DE70A4";
float myFloat = Float.intBitsToFloat(Integer.parseInt(hexString, 16));
}
catch (Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
But it is causing an Exception and telling me that Invalid int: "C2DE70A4"
Can anyone help me to make the Conversion? The Float value should be: -111.22
Thanks.
0xC2DE70A4 in decimal is 3,269,357,732, but an int's max value is 2,147,483,647. That's why you can't parse it -- the parsed value is too big to fit in an int.
You should parse the string as a long, then cast it to an int , and finally call Float.intBitsToFloat on that:
long asLong = Long.parseLong(hexString, 16);
int asInt = (int) asLong;
float myFloat = Float.intBitsToFloat(asInt);
// or, just
float myFloat = Float.intBitsToFloat((int)Long.parseLong(hexString, 16));
Detailed explanation:
Fundamentally, the problem is that C2DE70A4 represents an unsigned value, whereas ints in Java are signed. If you parse it as a long and then look at its bits (via Long.toBinaryString), you'll see:
11000010110111100111000010100100
That's a 32-length string, because toBinaryString omits leading 0s. So why didn't it fit in a 32-bit int? Because that binary string above represents an unsigned number. Or, more precisely, it's really shorthand for this signed, 64-bit, two's complement number:
0000000000000000000000000000000011000010110111100111000010100100
... which equals 3269357732 in decimal, which is out of the range of an int because an int is signed, meaning that the leftmost digit is the sign and not part of the number's magnitude (aka how "big" it is).
If you take that long and cast it to an int, it'll discard the leftmost 32 digits, leaving you with a 32-bit int 11000010110111100111000010100100 -- which corresponds to -1025609564 in decimal (again, in two's complement). If you then take that number and feed it to intBitsToFloat, you'll get -111.22.
change the hex string to 0xC2DE70A4..
public class Test {
public static void main (String[] args) {
String myString = "BF800000";
Long i = Long.parseLong(myString, 16);
Float f = Float.intBitsToFloat(i.intValue());
System.out.println(f);
System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
}
}

Coverting String to byte in Java

Having:
byte temp;
and a String which represents a binary number:
String binary = "00100100";
I want to convert this binary number to hex and store it in byte, so: as 00100100 binary equals 24 hex, I want to obtain:
temp = 24;
or
temp = 0x24;
Here's an example
String binary = "00100100";
int value = Integer.parseInt(binary, 2);
System.out.println(value);
System.out.println("0x" + Integer.toHexString(value));
Integer.parserInt(String, int)
Parses the string argument as a signed integer in the radix specified by the second argument.
So it will convert the binary String value to an integer with the specified base.
You can then use the Integer.toHexString(int) method to convert that value to a hex representation, appending the 0x if you really want to.

why Java throws a NumberFormatException

I got an exception while parsing a string to byte
String Str ="9B7D2C34A366BF890C730641E6CECF6F";
String [] st=Str.split("(?<=\\G.{2})");
byte[]bytes = new byte[st.length];
for (int i = 0; i <st.length; i++) {
bytes[i] = Byte.parseByte(st[i]);
}
That's because the default parse method expects a number in decimal format, to parse hexadecimal number, use this parse:
Byte.parseByte(st[i], 16);
Where 16 is the base for the parsing.
As for your comment, you are right. The maximum value of Byte is 0x7F. So you can parse it as int and perform binary AND operation with 0xff to get the LSB, which is your byte:
bytes[i] = Integer.parseInt(st[i], 16) & 0xFF;
Assuming you want to parse the string as hexadecimal, try this:
bytes[i] = Byte.parseByte(st[i], 16);
The default radix is 10, and obviously B is not a base-10-digit.
Java is very picky on signedness, it will not accept values to overflow. Thus, if you parse a Byte and it is larger than 127 (for example, 130 dec or 83 hex) you will get a NumberFormatException. Same happens if you parse an 8 digit hex number as an Integer (or a 16 digit hex number as a Long) and it starts with 8-F. Such values will not be interpreted as negative (two's complement) but as illegal.
If you think that this is anal retentive, I totally agree. But that's Java style.
To parse hex values as two's complement numbers either use a large enough integer type (for example, if you are parsing a Byte use Integer instead and type cast it to a byte later) or -- if you need to parse a Long, split the number in half it is 16 digits, then combine. Here's an example:
public static long longFromHex(String s) throws IllegalArgumentException {
if (s.length() == 16)
return (Long.parseLong(s.substring(0,8),16)<<32)|(Long.parseLong(s.substring(8,16),16)&0xffffffffL);
return Long.parseLong(s, 16);
}
Or, to read a Byte, just use Integer instead:
public static byte byteFromHex(String s) throws IllegalArgumentException {
int i = Integer.parseInt(s, 16);
if (i < 0 || i > 255) throw new IllegalArgumentException("input string "+s+" does not fit into a Byte");
return (byte)i;
}

Categories