Sigmalalalala
Sigmalalalala

Reputation: 127

Convert hex string value to hex int

How can I convert the hexstring into the form of hexint below?

string hexstring = "0x67";
int hexint = 0x67;

Upvotes: 1

Views: 845

Answers (3)

knittl
knittl

Reputation: 265966

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

Upvotes: 1

Christoph S.
Christoph S.

Reputation: 613

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.

Upvotes: 1

knittl
knittl

Reputation: 265966

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.

Upvotes: 1

Related Questions