Decimal to Hexadecimal in Java

One of my previous post, I had shown how to add HTML formatting to the Swing component. But while changing the color of the component while runtime, we have to change the color value to decimal to hexadecimal(r, g, b), to get it into HTML color format. So here is three way to convert decimal to hexadecimal value.

public class Hex
{
	public static void main(String args[])
	{
		int i = 14;
		String hexstr1 = Integer.toString(i, 16).toUpperCase();

		String hexstr2 = Integer.toHexString(i).toUpperCase();

		String hexstr3 = Integer.toHexString( 0x10 | 

i).substring(1).toUpperCase();

   		System.out.println("method 1:"+hexstr1); 
		System.out.println("method 2:"+hexstr2);

		System.out.println("method 3:" +hexstr3);
		
		/*output:
		method 1:E
		method 2:E
		method 3:E*/
     	}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: