Reputation: 615
I have a hexidecimal number (a color) stored in a String as followed: "ff62e6b8". I need to convert this back to an integer so I can use it as a color value again. I have tried the following:
Int i = Integer.parseInt("ff62e6b8", 16);
Int i = Integer.valueOf("ff62e6b8", 16);
Int i = Integer.decode("ff62e6b8");
But all of these methods raise exceptions. Am I missing something here?
Upvotes: 2
Views: 194
Reputation: 13415
Try with this :
int colorVal = Color.parseColor("#ff62e6b8");
Example :
myLayout.setBackgroundColor(Color.parseColor("#ff62e6b8"));
By this you will get colorVal = -10295624
.
And if you want to generate hexColor code back from the colorVal then use this :
String hexColor = String.format("#%06X", (0xFFFFFF & colorVal));
By this you will get hexColor = #62E6B8
.
Thanks.
Upvotes: 5
Reputation: 9206
FF62E6B8 is 4284671672 in decimal. It's simply to large to put it into int
. In int
you can store values which match the range <-2^31 - 1 ; 2^31 - 1>
. Try to use long
instead:
Long i = Long.parseInt("ff62e6b8", 16);
Long i = Long.valueOf("ff62e6b8", 16);
Long i = Long.decode("ff62e6b8");
Upvotes: 8
Reputation: 15827
the first one would be the good one
but ff62e6b8 exceeds the size of int (32 bit - signed), that's why an exception is raised.
Long l = Long.parseLong("ff62e6b8", 16);
should do the job
Upvotes: 1
Reputation: 3440
String hex = "1B";
int val = Integer.parseInt(hex, 16);
That is the correct conversion.
Upvotes: 0