| Displaying With Hex Strings |
| Hex Literals |
| Hex vs Decimal vs Binary |
| Table of Hex digits |
| Hex Color Numbers |
| Links |
// convert a single byte b to a 2-char hex string // with possible leading zero. String s2 = Integer.toString( ( b & 0xff ) + 0x100, 16 /* radix */ ).substring( 1 );The method com.mindprod.common11.StringTools. toLzHexString will apply the necessary lead zeros for you:
// Available in download http://mindprod.com/products1.html#COMMON11 import com.mindprod.common11.StringTools; ... // Prepare unsigned hex string padded out to 4 places with lead zeroes. final String display = StringTools.toHexString( value, 4 /* desired length */ );You can convert a hex String to internal binary like this:
/* convert a hex String to int */ // Note, there is no lead 0x, case insensitive String g = "af0c99"; 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.
And here is how to go the other way from a hex string back to a byte array: Here’s an alternate implementation of charToNibble. 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.Here is how you can convert a String to hex for display so you can tell precisely what each character is.
Use can also use Printwriter.printf( "%x", i ) to display a hex number.
// example of a hex 0x literal int a = 0x8cf;
| 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 |
![]() |
and suggestions to improve this page to Roedy Green : | ||
| Canadian Mind Products | |||
| mindprod.com IP:[65.110.21.43] | |||
| Your face IP:[38.103.63.62] | ![]() | ||
| You are visitor number 160,013. | |||
| You can get a fresh copy of this page from: | or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror) | ||
| http://mindprod.com/jgloss/hex.html | J:\mindprod\jgloss\hex.html | ||