| 1 | /* |
| 2 | * $Id: HexFormatter.java,v 1.1.1.5 2004/05/25 20:23:30 hastings Exp $ |
| 3 | * |
| 4 | * (c) Copyright, Moebius Solutions, Inc., 2004 |
| 5 | * |
| 6 | * All Rights Reserved |
| 7 | * |
| 8 | * This material may be reproduced by or for the U. S. Government |
| 9 | * pursuant to the copyright license under the clause at |
| 10 | * DFARS 252.227-7014 (OCT 2001). |
| 11 | */ |
| 12 | |
| 13 | package com.moesol.util; |
| 14 | |
| 15 | /** |
| 16 | * Format hex numbers with leading padding if needed. |
| 17 | */ |
| 18 | public class HexFormatter { |
| 19 | /** |
| 20 | * @param value value to format as hex |
| 21 | * @param width width of all output |
| 22 | * @return hex formatted String |
| 23 | */ |
| 24 | public static String format(long value, int width) { |
| 25 | return format(value, width, '0'); |
| 26 | } |
| 27 | /** |
| 28 | * |
| 29 | * @param value value to format as hex |
| 30 | * @param width width of all output |
| 31 | * @param pad_char character to insert if padding is needed |
| 32 | * @return hex formatted String |
| 33 | */ |
| 34 | public static String format(long value, int width, char pad_char) { |
| 35 | StringBuffer result = new StringBuffer(); |
| 36 | appendPaddedHex(result, value, width, pad_char); |
| 37 | return result.toString(); |
| 38 | } |
| 39 | public static void appendPaddedHex( |
| 40 | StringBuffer r, |
| 41 | long value, |
| 42 | int width, |
| 43 | char pad_char) |
| 44 | { |
| 45 | String hex = Long.toHexString(value); |
| 46 | for (int i = width - hex.length(); i > 0; i--) { |
| 47 | r.append(pad_char); |
| 48 | } |
| 49 | r.append(hex); |
| 50 | } |
| 51 | } |