Last updated 2004-06-29 by Roedy
Green ©1996-2004 Canadian Mind Products
Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
You are here : home : Java Glossary : H words : hexadecimal.
String hex = Integer.toString(i , 16 /* radix */ );
That won't apply any lead zeroes. Here is how to get a lead 0 for a fixed two character hex representation of a byte:
// convert a byte b to 2-char hex string // with possible leading zero. String s2 = Integer.toString( ( b & 0xff ) + 0x100, 16 /* radix */ ).substring( 1 );
You can convert a hex String to internal binary like this:
int i = Integer.parseInt(g.trim(), 16 /* radix */ );
The following code looks more complicated, but is considerably faster. It also handles a byte array, not just a single byte.
// Fast convert a byte array to a hex string // with possible leading zero. public static String toHexString ( byte[] b ) { StringBuffer sb = new StringBuffer( b.length * 2 ); for ( int i=0; i<b.length; i++ ) { // look up high nibble char sb.append( hexChar [( b[i] & 0xf0 ) >>> 4] ); // look up low nibble char sb.append( hexChar [b[i] & 0x0f] ); } return sb.toString(); } // table to convert a nibble to a hex char. static char[] hexChar = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f'};
And here is how to go the other way from a hex string back to a byte array:
Since the computer uses binary internally, it makes no sense to talk about converting an int from hex to decimal or back, only a String.
In Java you can use hex literals like this
int a = 0x8cf;
The computer chip works internally in binary (base 2 numbers), with numbers made only of the digits 0 and 1, low voltage/high voltage. Binary numbers are somewhat bulky to write out, so they are usually written in base 16, hex. It is very easy to convert hex to binary and visa versa using the following table. For example, the hex number 8cf is 100011001111 in binary. Converting between decimal and hex is more difficult. You must do successive divisions and moduluses by 10 or 16.
| Decimal | Hex | Binary |
|---|---|---|
| 0 | 0 | 0000 |
| 1 | 1 | 0001 |
| 2 | 2 | 0010 |
| 3 | 3 | 0011 |
| 4 | 4 | 0100 |
| 5 | 5 | 0101 |
| 6 | 6 | 0110 |
| 7 | 7 | 0111 |
| 8 | 8 | 1000 |
| 9 | 9 | 1001 |
| 10 | a | 1010 |
| 11 | b | 1011 |
| 12 | c | 1100 |
| 13 | d | 1101 |
| 14 | e | 1110 |
| 15 | f | 1111 |
home |
Canadian Mind Products | |||
| mindprod.com IP:[24.87.56.253] | ||||
| Your IP:[80.134.30.163] | ||||
| You are visitor number 24740. | ||||
| Please send errors, omissions and suggestions | ||||
| to improve this page to Roedy Green. | ||||
| You can get a fresh copy of this page from: | or possibly from your local J: drive mirror: | |||
| http://mindprod.com/jgloss/hex.html | J:\mindprod\jgloss\hex.html | |||