0

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.

6
  • 1
    No, that's not possible. System.out.println(number); will always output in decimal, not hexadecimal. You can use System.out.format. Commented Jul 19, 2017 at 8:32
  • I do not want to print it. I want to use it as Integer. e.g int i = 0x5F2A; Commented Jul 19, 2017 at 8:35
  • int number = Integer.parseInt(str, 16); is transforming a String to an int with base 16(hex). Commented Jul 19, 2017 at 8:37
  • @AshutoshVaidya Then you should update your question, because right now it states that the code you posted should show the output 0x5F2A. Commented Jul 19, 2017 at 8:43
  • Thank you @ErwinBolwidt I was not aware numbers could be used interchangeably. Commented Jul 19, 2017 at 8:47

3 Answers 3

4

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!

Sign up to request clarification or add additional context in comments.

6 Comments

It is still the string. I want integer.
@AshutoshVaidya You can do the conversion to Integer through Integer.parseInt(String, int).
It would give me a decimal number as 24362. I need as int n = 0x5F2A;
@AshutoshVaidya You are confusing storing the variable vs printing the variable
@AshutoshVaidya 0x5F2A is only a represenation of number 24362. And this is only a presentation for binary 101111100101010.
|
1

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

1 Comment

Thank you. I was not aware numbers could be used interchangeably.
0

See here

Integer.parseInt(/*your String*/, 16);

16 is the radix for hexadecimal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.