Thursday 9 May 2013

How to Use Hexadecimal Values in Java

You can tell Java that a number is in hexadecimal (base 16) by prefixing it with 0x.
In the example below, the variable hexadecimal_1F is assigned the value 0x1F i.e. hexadecimal 1F. The program then displays the value in decimal (base 10).
 
UNIX > cat prog23.java
public class prog23
{
public static void main (String args[])
  {
  int hexadecimal_1F = 0x1F;
  System.out.println
  ("hexadecimal 1F = " + hexadecimal_1F);
  }
}
UNIX > javac prog23.java
UNIX > java prog23
hexadecimal 1F = 31
UNIX >
 
You can check the result yourself by converting hexadecimal 1F to decimal (base 10) like this:
 
Hexadecimal 1F = (in decimal or base 10) (1 x 16) + 15 = 31
 
If you have a Java book on Amazon, which you would like to advertise here for free, please write to me at international_dba@yahoo.co.uk.