Java - Convert hex to decimal - make a string = the correct number
Solution 1
To convert a hex string to an int, you could simply use Integer.parseInt(str, 16)
.
Solution 2
Why dont you try which is already available.
Color.decode("hex string");
Solution 3
Integer.parseInt(String str)
works only if str
contains integer. Like if you have string as str="12345"
Integer.parseInt(str)
results 12345
as integer.
But in your case mentioned you are passing either one of "A", "B", "C", "D", "E", "F"
.
Michael Garrison
Currently majoring in Information Technology and minoring in Computer Science. I am interested in designing websites with functionality with languages like JavaScript, PHP, MySQL, etc. Hoping to open up my own business some day doing outside IT consulting for small businesses.
Updated on December 12, 2020Comments
-
Michael Garrison over 3 years
ERROR WAS DUE TO A MISTAKE WHICH WAS OVERLOOKED
I recently created a Java program that converts an rgb value to hexadecimal. Now I am trying to make a program that will do the opposite. I already figured out the algorithm I am going to use, I just need to convert the characters
A - F
to the values10 - 15
. Seems simple right? This is where I hit my problem.Here is the code I have so far. A string is fed into
nums()
which then checks it against the arrayabc
. Once a match is found it takes takes the stringa
and converts it to an integer, then takesi
and will add 10 in order to get the right number.class TextToNum { String[] abc = { "A", "B", "C", "D", "E", "F" }; public int nums(String a) { for(int i = 0; i < abc.length; i++) { if (a == abc[i]) { a = Integer.parseInt(a.trim()); a = i + 10; } } return a; } }
The errors I get are:
gbConv.java:52: incompatible types found : int required: java.lang.String a = Integer.parseInt(a.trim()); ^ rgbConv.java:53: incompatible types found : int required: java.lang.String a = i + 10; ^ rgbConv.java:56: incompatible types found : java.lang.String required: int return a; ^
It is obvious that something is wrong with the
Integer.parseInt()
but I am not sure how to fix it. I have been looking on the web and I can't find anything. Any suggestions / tutorials would be a great help.